Plotly express not showing plots in PyCharm SciView - python-3.x

I'm trying to render a Plotly graph in PyCharm's SciView-Plots panel (using PyCharm Professional 2020.3).
A simplified version of what I'm running is:
import plotly.express as px
import plotly.io as pio
pio.renderers.default = 'png'
fig = px.scatter(data)
fig.show()
This code runs, but does not show a plot. Instead I see a printout in the console that looks like:
{'image/png': 'iVBORw0KGgoAAAANSUh<cropped for brevity...>'}
I was working on following this article, but the solutions there don't seem to work: how can I see plotly graphs in pycharm?

Sciview will support matplotlib.pyplot.show, therefore you can export to png, then display the png using matplotlib.pyplot.show
import io
import numpy as np
import plotly.express as px
import plotly.io as pio
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
pio.renderers.default = 'png'
def plot(fig):
img_bytes = fig.to_image(format="png")
fp = io.BytesIO(img_bytes)
with fp:
i = mpimg.imread(fp, format='png')
plt.axis('off')
plt.imshow(i, interpolation='nearest')
plt.show()
x = np.arange(0, 5, 0.1)
y = np.sin(x)
fig = px.scatter(x, y)
plot(fig)
works with Pycharm professional 2019.3

Related

Using Python I want to set the font as a custom from dafont.com but it's not working

Tried importing this font but there isn't anything on the internet to explain how to do it.
https://www.dafont.com/oceanic-drift.font
I tried doing it on my own so I don't think you'll find it useful but I'm putting the code anyway:
import matplotlib.font_manager as font_manager
from fontTools.ttLib import TTFont
font = TTFont('/Windows/Fonts/oceanicdrift.ttf')
font_dirs = ['C:\\Users\\User\\AppData\\Local\\Microsoft\\Windows\\Fonts\\oceanicdrift.ttf', ]
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
font_manager.fontManager.ttflist.extend(font_files)
figure(figsize=(15, 12))
ax = plt.gca()
plt.text(0.5, 0.5, 'TEST text', color='Black', fontsize=30, fontname=font)
plt.show()
ax = plt.subplot()
fpath = os.path.join(mpl.get_data_path(), r"C:\Users\User\Desktop\oceanicdrift.ttf")
prop = fm.FontProperties(fname=fpath)
plt.text(0.5, 0.5, 'TEST text', color='Black', fontsize=30, fontproperties=prop)
plt.show()
After some more research I came to this.
Here is what you need to import for it to work:
import os
import matplotlib as mpl
import matplotlib.pyplot as plt

How to create own cmap?

I tried the following code, but the matching name is used wrong. How to give a name to the created colour map, please?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
cMap = []
for value, colour in zip([28800, 29000, 29200, 29400, 29600, 29800, 30000],["darkblue", "mediumblue", "royalblue", "cornflowerblue", "dodgerblue", "skyblue", "paleturquoise"]):
cMap.append((value, colour))
customColourMap = LinearSegmentedColormap.from_list("pri_c", cMap)
x=np.arange(9)
y=[9,2,8,4,5,7,6,8,7]
plt.scatter(x,y, c=y,cmap='pri_c')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Virdis colormap")
plt.colorbar()
plt.show()
If you are working with matplotlib >= 3.5 then you can register the color map with plt.colormaps.register.
If you are using an older version, use plt.register_cmap.
You need to map you color values between 0 and 1 so your code would look something like
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
color_values = np.array([28800, 29000, 29200, 29400, 29600, 29800, 30000])
color_values -= color_values[0]
color_values = color_values / color_values[-1]
color_names = ["darkblue", "mediumblue", "royalblue",
"cornflowerblue", "dodgerblue", "skyblue",
"paleturquoise"]
cMap = list(zip(color_values, color_names))
customColourMap = LinearSegmentedColormap.from_list("pri_c", cMap)
# if mpl >= 3.5
plt.colormaps.register(customColourMap)
# if mpl < 3.5
# plt.register_cmap(cmap=customColourMap)
x=np.arange(9)
y=[9,2,8,4,5,7,6,8,7]
plt.scatter(x,y, c=y,cmap='pri_c')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Virdis colormap")
plt.colorbar()
plt.show()

How to customize a Graph using Matplotlib

I need help to customize a graph using Matplotlib.
I want to draw a graph like this.
My python code is:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
data=np.loadtxt('input.txt', delimiter = ',')
x = np.arange(0,64)
y = np.arange(0,64)
fig, ax = plt.subplots()
im = ax.imshow(data)
#customize colorbar
cmap = mpl.colors.ListedColormap(['royalblue','blue','red'])
im = ax.contourf(y,x,data,cmap=cmap)
fig.colorbar(im)
plt.show()
and my output is:
So what should i do ?
Thank you.

Matplotlib.plot not found

I installed Matplotlib via Anaconda from here: https://anaconda.org/conda-forge/matplotlib
I used the very first command in Anaconda prompt.
But when I tried to plot from python (Spyder) as the following, I get the message:
ModuleNotFoundError: No module named 'matplotlib.plot'
import numpy as np
import matplotlib.plot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x,y)
I have installed numpy, pandas and such using the same method and they work well.
How can I fix this?
Thank you so much.
matplotlib.pyplot is a state-based interface to matplotlib. pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation. Therefore, whenever trying to work with graphs and what is commonly known and informally often referred as matplotlib you should import matplotlib.pyplot as plt:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x,y)

Not getting plotly graph in Jupyter notebook when I close and open the notebook again?

I have created many graphs using plotly library in jupyter notebook. I saved the file and exit. My graph is not appearing when I re-opened the jupyter notebook again? I need to run the code again in order to get my graph back. Also, I have sent my saved ipynb file to my friend and he is unable to see the plot..Any suggestions?
I used py.offline.init_notebook_mode(connected=True)
import plotly.plotly as py
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go
import ipywidgets as widgets
import numpy as np
from scipy import special
import datetime
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.figure_factory as ff
init_notebook_mode
from math import floor
from plotly import tools
from plotly.graph_objs import *
from IPython.display import display
import plotly.tools as tls
import json
import math
from plotly.widgets import GraphWidget
import plotly.io as pi
data = [go.Bar(
x = dplot['Boxoffice_US_Mil'],
y = dplot['dircount'],
orientation = 'h',
marker = dict(
color = 'rgb(67,262,402)'))]
# Declaring the Title and margins
layout = dict(
title = 'Average Box Office collections by Director who have directed more than 3 movies',
margin = go.Margin(
l = 210,
r = 100,
pad = 1),
xaxis = dict(
title = 'Average Box Office Collection (US mil)'),
yaxis = dict(
title = ' Director (Number of Movies)',
tickfont = dict(
size = 12,)))
fig = go.Figure(data = data, layout = layout)
iplot(fig)

Resources