been playing around with plotly for Python, but constantly running into the same error message stated above. I installed plotly on Anaconda, getting the error message both on Jupyter and Spyder respectively:
#data manipulation
import pandas as pd
import numpy as np
#loading csv
df = df = pd.read_csv(r'C:\Users\hendev\Desktop\FIFA18 - Ultimate Team players.csv')
import plotly.graph_objs as go
# prepare data
x2017 = df.overall[df.added_date == 2017]
x2018 = df.overall[df.added_date == 2018]
trace1 = go.Histogram(
x=x2017,
opacity=0.75,
name = "2017",
marker=dict(color='rgba(171, 50, 96, 0.6)'))
trace2 = go.Histogram(
x=x2018,
opacity=0.75,
name = "2018",
marker=dict(color='rgba(12, 50, 196, 0.6)'))
data = [trace1, trace2]
layout = go.Layout(barmode='overlay',
title=' Rating added in 2017 and 2018',
xaxis=dict(title='students-staff ratio'),
yaxis=dict( title='Count'),
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
Any idea what I'm doing wrong?
Note: $ from plotly.plotly import iplot will work only till plotly v3.10.0 The plotly.plotly module has been deprecated in plotly v4.0. Check your version first:
$ python3 -c 'import plotly; print(plotly.__version__)' # for Python 3
$ python -c 'import plotly; print(plotly.__version__)' # for Python 2
v4.0 onwards, the functionality has been split into two modes: online and offline.
Online
If you wish to have the figures rendered online, you will now need to import chart-studio and use
from chart_studio.plotly import plot, iplot
Offline
If you want to render the images locally, you have multiple options:
from plotly.offline import iplot
# your code
iplot(fig)
or
from plotly.subplots import make_subplots
fig = make_subplots(# your args)
# your code
fig.show()
or
import plotly.io as pio
# your code
pio.show(fig)
or
import plotly.graph_objects as go
fig = go.Figure(# your args)
# your code
fig.show()
You can read up more on the renderers here.
You forgot to import it
from plotly.plotly import iplot
You need to call iplot with py:
import plotly.plotly as py
py.iplot(fig)
Just in case, if you want to plot in offline mode and save plot as file.hmtl:
import plotly.offline as py
plotly.offline.init_notebook_mode()
py.iplot(fig, filename="file.html")
Do not be afraid of looking through in documentation: here you can find nice and understandable examples how to use plotly properly. For example, here you can see how to plot simple bar chart, etc.
For Jupyter Notebook and Kaggle Notebooks, this helped me.
from plotly.offline import iplot
Related
I`m making a 'Rolling Dice' project with Plotly. before that, I install Plotly using the command:
$ python -m pip install --user plotly
When I run 'from plotly.gragh_objs import Bar, layout', I got the error message:
'ModuleNotFoundError: No module named 'plotly.gragh_objs''
I try to upgrade pip, but it doesn`t work. anyone know where are the problems.
My code as follow:
from plotly.gragh_objs import Bar, Layout
from ploty import offline
from dice import Die
die = Die()
results = []
for roll_num in range(1000):
result = die.roll()
results.append(result)
frequencies = []
for value in range(1, die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
x_values = list(range(1, die.num_sides+1))
data = [Bar(x=x_values, y=frequencies)]
x_axis_config = {'title':'Result'}
y_axis_config = {'title':'Frequency of Result'}
my_layout = Layout(title='Results of rolling one D6 1000 times',
xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data':data, 'layout':my_layout}, filename='d6.html')
The import code should be as follows:
from plotly.graph_objects import Bar, Layout
from plotly import offline
I am following a python tutorial about the use of plotly.
Here are some commands I have to run to import functions and methods I will use
import plotly.plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
However, when I run commands on my jupyter nootbook, it says the use of plotly is deprecated and it recommends me to use the module chart_studio instead (error points to line import plotly.plotly as py):
ImportError: The plotly.plotly module is deprecated, please install
the chart-studio package and use the chart_studio.plotly module
instead.
So I run
pip install chart_studio
and try to replace the line above with functions and methods coming from the chart_studio module.
Here is my code:
import chart_studio.plotly as py
import plotly.graph_objects as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
data = dict(type= 'cloropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale = 'Portland',
text = ['text 1','text 2','text 3'],
z = [1,2,3],
colorbar = {'Title':'Colorbar title goes here'})
mylayout = dict(geo={'scope':'usa'})
choromap = go.Figure(data = [data], layout=mylayout, skip_invalid=True)
iplot(choromap)
The problem is that, when running the final line iplot(choromap), I get this empty graph
While in the tutorial this other graph appears
What is wrong?
Please note that I installed cufflinks-0.17.3 plotly-4.5.4
Did you try to cleanly install plotly?
Uninstall plotly using pip
!pip uninstall plotly
Then uninstall plotly using conda
!conda uninstall plotly
After that, install the last version using pip
!pip install plotly
check Plotly version
import plotly
plotly.__version__
SOLVED
In my code there were 2 errors:
at line
type= 'cloropleth',
I had the mispelled value 'cloropleth', where the correct value is 'choropleth',
and then at line
colorbar = {'Title':'Colorbar title goes here'})
I had 'Title', where the correct key is 'title' (lowercase).
Fixed them and now the map is correctly displayed.
Also, it was not necessary to install chart_studio.
So in the end the correct code is:
import plotly.graph_objects as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
data = dict(type= 'choropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale = 'Portland',
text = ['text 1','text 2','text 3'],
z = [1,2,3],
colorbar = {'title':'Colorbar title goes here'})
mylayout = dict(geo={'scope':'usa'})
choromap = go.Figure(data = [data], layout=mylayout)
iplot(choromap)
I want to plot with latex and other fonts but only latex font seems to be available. How can I enable other fonts with usetex?
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='Arial')
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()
Plotted image
Using usetex=True
You have to use your own LaTeX header for matplotlib.
You can then use the fontpackages to select fonts.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True
plt.rcParams['text.latex.preamble'] = r'''
\usepackage{mathtools}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
% more packages here
'''
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Result:
using the pgf backend
You get the most flexibility by using the pgf backend. This needs a recent LaTeX installation in the system.
For me, the most practical approach is to have a matplotlibrc and a header-matplotlib.tex and just include the texfile in the matplotlibrc. However, because matplotlib runs tex in a tmp directory, you need to add the current directory to the TEXINPUTS.
Example:
matplotlibrc
backend: pgf # use the pgf backend
pgf.rcfonts : False # setup the fonts yourself in the header
text.usetex : True
text.latex.unicode : True
pgf.texsystem : lualatex
pgf.preamble : \input{header-matplotlib.tex}
header-matplotlib.tex
\usepackage{fontspec}
\setsansfont{Arial} # for the example I used Fira Sans
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
% more packages here
pgf_plot.py (This got much smaller, as we are setting the options in `matplotlibrc)
import matplotlib.pyplot as plt
import numpy as np
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Run using
$ TEXINPUTS=$(pwd): python pgf_plots.py
Result:
This approach can be extended, to match the fonts and font size of the plot to the ones used in your document, see the example here:
https://github.com/Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE/tree/master/examples/use_system_latex
The following piece of code works fine when I run the script in pycharm
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches
c1 = mpatches.Patch(color="green",label="No Traffic")
c2 = mpatches.Patch(color="red",label="Traffic")
df = predict_df.limit(100).toPandas()
colors = {0:"red",1:"green"}
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df["avgSpeed"],df["vehicleCount"],df["avgMeasuredTime"],c=df["prediction"].apply(lambda x: colors[x]),s=100,marker="o")
ax.set_xlabel('avgMeasuredTime')
ax.set_ylabel('avgSpeed')
ax.set_zlabel('vehicleCount')
plt.title("BiKmeans Traffic Data")
plt.legend(handles=[c1,c2])
plt.show()
I have installed matplotlib using pip, also based on some similar questions tried to install as sudo apt-get install python-matplotlib
but I get the same error in Zepplin,
File "/home/benjamin/.local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 280, in <lambda>
key=lambda col: col.do_3d_projection(renderer), AttributeError: 'PathCollection' object has no attribute 'do_3d_projection'
The version of matplotlib is 2.2.0
I'm trying to use cufflinks locally to generate plotly graphs from a pandas Dataframe
However, when I try and configure cufflinks in a python console, it then goes into ipython mode:
>>> import cufflinks as cf
>>> cf.set_config_file(offline=True)
In :
Subsequently, when I try and generate a plot, nothing appears:
In : df.iplot(kind='bar', barmode='stack', filename='cufflinks/test')
In :
Can cufflinks be used offline without a plotly account?
I think the issue is setting the filename argument in the iplot call.
df.iplot(kind='bar', barmode='stack')
http://nbviewer.jupyter.org/gist/santosjorge/5fdbe947496faf7af5e6
Edit if it is possible to do this with plotly, you can pass your cufflinks-generated figure to plotly.plot:
import cufflinks as cf
import plotly as py
fig = df.iplot(kind='bar', barmode='stack', asFigure=True)
py.offline.plot(fig)
This worked for me (assuming you have a folder name cufflinks):
import plotly.plotly as py
import plotly
import cufflinks as cf
import pandas as pd
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode,
plot, iplot
init_notebook_mode(connected=True)
cf.go_offline()
# Offline html saving
df = pd.DataFrame(np.random.randn(1000, 3), columns=['A','B','C']).cumsum()
fig = df.iplot(asFigure=True)
plotly.offline.plot(fig,filename="cufflinks/example.html")
#elsherbini and #Charon: unfortunately I have not enough credentials to comment, so I have to write a new answer.
your code pointed me into the right direction, but with the latest cufflinks version it goes even simpler:
import cufflinks as cf
df.iplot(kind='bar', barmode='stack', filename="my_barplot" , asPlot=True)
This code will generate a my_barplot.html file and open the plot in the default web browser.
And this code is scriptable.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from plotly import __version__
import plotly.graph_objs as go
import cufflinks as cf
from plotly.offline import download_plotlyjs,plot,iplot
cf.go_offline()
df = pd.DataFrame(np.random.randn(100,4),columns = 'A B C D'.split())
print("\nHead for df : \n",df.head())
df2 = pd.DataFrame({'Category':['A','B','C'],'Values':[32,43,50]})
print("\ndf2 : \n",df2)
df.iplot(asPlot=True)
just use this:
import cufflinks as cf
cf.set_config_file(offline=True)