I was trying to plot choropleth map using plotly but getting a blank output.I am not getting any map.here is my code-
input-
import plotly.plotly as py
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)
%matplotlib inline
data = dict(type = 'choropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale= 'Portland',
text= ['text1','text2','text3'],
z=[1.0,2.0,3.0],
colorbar = {'title':'Colorbar Title'})
layout = dict(geo = {'scope':'usa'})
choromap = go.Figure(data=[data] , layout=layout)
iplot(choromap )
output-
it is a blank screen. I am sharing my screenshot.What is the issue?
Thank you in advance
https://drive.google.com/file/d/14R6zfNxnefBoe3RFlFH2YunlTbrFzfRX/view?usp=sharing
Just double click on the white space and you will get the desired output.
This worked for me.
Thanks
Related
I am using plotly. I am getting the plot. The problem is, I am using seasons as colormap. I have used 1 for fall, 2 for winter, ..,4 for summer. Now, the colomap shows these numbers and also 1.5, 2.5 etc. I want to show Names instead of numbers
My code:
import plotly.express as px
from plotly.offline import plot
import plotly
fig = px.scatter_3d(df, x=xlbl, y=ylbl, z=zlbl,
color=wlbl,opacity=0,
color_continuous_scale = plotly.colors.sequential.Viridis)
temp_name = 'Temp_plot.html'
plot(fig, filename = temp_name, auto_open=False,
image_width=1200,image_height=800)
plot(fig)
Present output:
You can modify the coloraxis by adding the following lines to your code:
cat_labels = ["Fall", "Winter", "Spring", "Summer"]
fig.update_coloraxes(colorbar=dict(ticktext=cat_labels,
tickvals=list(range(1, len(cat_labels)+1))))
Sample output with random data:
I have a huge problem with Jupyter Notebook.
When he builds graphs using the plot packet, to display the next graph I have to reload the dataset, otherwise an error pops up: TypeError: list indices must be integers or slices, not str. When I reopen the project, all the graphs created using Plotly are not visible, just a white background and I have to reload them if I want to see them, and everything after reloading the dataset, that is:
1) I open the project in Jupyte Notebook, all graphs created by Plotly are not visible (others from Seaborn for example are visible.
2) I load the Plotly charts, but I can load them one by one, because first I have to load the dataset, then the chart, and so an error occurs to all Plotly charts differently: TypeError: list indices must be integers or slices
what can I do about it how to fix it? it seriously hinders the work
this is my libraries:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import plotly.offline as py
import plotly.graph_objs as go
import plotly.tools as tls
This is an example of this error, but if I load the dataset again and again load this plot everything will be ok:
and the example of the code of plot:
#Distribution of credit risk in dataset (target variable)
#Size of the plot
figsize=(10,5)
#Sums of good and bad credits in the dataset
goodCount = data[data["Risk"]== 'good']["Risk"].value_counts().values
badCount = data[data["Risk"]== 'bad']["Risk"].value_counts().values
#Bar fo good credit
trace0 = go.Bar(x = data[data["Risk"]== 'good']["Risk"].value_counts().index.values,
y = data[data["Risk"]== 'good']["Risk"].value_counts().values,
name='Good credit',
text= goodCount,
textposition="auto",
marker = dict(color = "green", line=dict(color="black", width=1),),opacity=1)
#Bar of bad credit
trace1 = go.Bar(x = data[data["Risk"]== 'bad']["Risk"].value_counts().index.values,
y = data[data["Risk"]== 'bad']["Risk"].value_counts().values,
name='Bad credit',
text= badCount,
textposition="auto",
marker = dict(color = "red", line=dict(color="black", width=1),),opacity=1)
#Creation of bar plot
data = [trace0, trace1]
layout = go.Layout()
layout = go.Layout(yaxis=dict(title='Count'),
xaxis=dict(title='Risk variable'),
title='Distribution of target variable in the dataset')
fig = go.Figure(data=data, layout=layout)
fig.show()
I was trying to create some heatmap using plotly3.10 and I encountered one problem that the
column names are not displayed full in ylabel.
import pandas as pd
import plotly.figure_factory as ff
from plotly.offline import plot, iplot, init_notebook_mode
df = pd.util.testing.makeDataFrame()
df.columns = ['this_is_long_column_name','another_column_name','yet_another_column_name','price']
df_corr = df.corr()
z = df_corr.values
fig = ff.create_annotated_heatmap(z,showscale=True,
x=df_corr.columns.values.tolist(),
y=df_corr.columns.values.tolist()
)
iplot(fig)
I got this image:
Question
How to show the full column name in ylabels?
How to show xlabel on both top and bottom with larger fontsizes?
How to show only 2 significant numbers, like df.round(2) only in plot?
Have you tried manually specifying the margins? E.g.:
import plotly.graph_objs as go
layout = go.Layout(
margin=dict(l=80, r=80, t=100, b=80)
)
This might work for you:
import numpy as np
import pandas as pd
import plotly
import plotly.offline as py
import plotly.graph_objs as go
import plotly.figure_factory as ff
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=False)
df = pd.util.testing.makeDataFrame()
df.columns = ['this_is_long_column_name','another_column_name','yet_another_column_name','price']
df_corr = df.corr()
z = df_corr.round(2).values
fig = ff.create_annotated_heatmap(z,showscale=True,
x=df_corr.columns.values.tolist(),
y=df_corr.columns.values.tolist()
)
layout = go.Layout(margin=dict(l=200, r=50, t=100, b=50))
fig.layout.update(layout)
iplot(fig)
Gives:
I'm using Plotly with Python and pandas df to create a gantt-chart with a rangeslider. However, the data on rangeslider is not visible and instead of appearing with the colors as in the actual plot, it appears white-colored.
Here is part of the code I'm using:
from plotly.offline import plot
import plotly.figure_factory as ff
colors = {0: 'rgb(46, 137, 205)',
1: 'rgb(58, 149, 136)',
2: 'rgb(114, 44, 121)'}
fig = ff.create_gantt(df, colors=colors, index_col='num_faces', show_colorbar=True,
bar_width=0.2, showgrid_x=True, showgrid_y=True, group_tasks=True)
fig['layout']['xaxis']['rangeselector']['visible'] = False
fig['layout']['xaxis']['rangeslider'] = dict(bgcolor='#000')
fig['layout']['xaxis']['type'] = 'date'
# yaxis customisation
fig['layout']['yaxis']['title'] = 'Number of people'
# plot customisation
fig['layout']['title'] = 'Time Spent with People'
Just for display options, I have set the background color of the rangeslider to black and here is the plot result. As you see, data is there but not colored.
Is there any solution on how to make my data visible on the rangeslider?
Thanks in advance.
I'm using plotly v.2.2.1 and Python 3.5.2.
I am working with plotly offline and am able to generate an html file using
plotly.offline.plot({"data": data, "layout": layout})
It works great. The graph is generated correctly and the html file gets saved to my current directory.
What I want, though is, using plotly offline, is to have an image (.png, .jpg, etc.) file saved instead. Am I on the right track? What do I need to do from here?
Try this
import plotly.offline
import plotly.graph_objs as go
plotly.offline.plot({"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": go.Layout(title="hello world")},
image='jpeg', image_filename='test')
and open it in Chrome
I found the solution in the documentation here:
https://plot.ly/python/static-image-export/
So a minimal example would be:
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
N = 1000
random_x = np.random.randn(N)
random_y = np.random.randn(N)
trace = go.Scatter(
x = random_x,
y = random_y,
mode = 'markers'
)
data = [trace]
py.image.save_as({'data':data}, 'scatter_plot', format='png')
Simple way of using python plotly graphs offline:
1) Write import statements
import plotly.graph_objs as go
import plotly as plotly
import plotly.express as px
2) write your plotly graph code e.g.
data = px.data.gapminder()
data_canada = data[data.country == 'Canada']
fig = px.bar(data_canada, x='year', y='pop',
hover_data=['lifeExp', 'gdpPercap'], color='lifeExp',
labels={'pop':'population of Canada'}, height=400)
3) name your figure (provide reader-friendly name :) )
plotly.offline.plot(fig, filename= output_filename + ".html")
4) Well-done! Please add comments, if you like my answer!
one possibility using ipython notebook is to display the graph and then choose the option "Download plot as png" manually.
Here says to use
import plotly.plotly as py
# Generate the figure
trace = Bar(x=[1,2,3],y=[4,5,6])
data = [trace]
layout = Layout(title='My Plot')
fig = Figure(data=data,layout=layout)
# Save the figure as a png image:
py.image.save_as(fig, 'my_plot.png')