How to disable a line in plotly at start? - python

I would like to show the lines but with some are disabled. So just like when I show it normally and then click on its name to unshow/disable the line.
I am using python.

visible attribute of a trace as "legendonly" makes a line behave in way you describe
Below code generates a figure with 10 lines, then sets visible to legendonly for lines 3 to 10. Clicking on legend makes them visible.
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({f"line{i+1}":np.random.uniform(i,i+2,100) for i in range(10)})
px.line(df, x=df.index, y=df.columns).update_traces(visible="legendonly", selector=lambda t: not t.name in ["line1","line2"])

Related

Plotly Express choropleth map not showing in visual studio code

Below shown the syntax used to get a map visualized and plotted from Plotly Express - choropleth from a "csv" DataFrame.
import pandas as pd
import numpy as np
import plotly.express as px
df = "//location.csv"
fig = px.choropleth(data_frame = df,
locations= df["location"],
locationmode='country names',
color=df["location"],
hover_name=df["location"],
title = "Location Data",
color_continuous_scale = px.colors.sequential.Oranges)
fig["layout"].pop("updatemenus")
fig.show()
However, when I use the above syntax on the Visual Studio Code Jupyter Notebook, the map does not get visualized and plotted. Which is shown as below,
But when I run the same code on the Anaconda Jupyter Notebook, I do get the map visualized and plotted as shown below,
Why isn't the map not getting visualized and plotted on VS code, and is there any way to resolve this issue on VS code?
I was interested in this question because I usually work with jypyterLab. I ran it based on this answer, and when I ran it in vscode, it displayed correctly in my default browser. The code I ran was based on the code in the official reference.
import plotly.express as px
from plotly.offline import plot
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, locations="iso_alpha",
color="lifeExp", # lifeExp is a column of gapminder
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
# fig.show()
plot(fig)

Stuck on How to Display Hover Data in Specific Format

I am testing some plotly code here.
import plotly.express as px
# find business profits
pd.options.display.float_format = '{:.2f}'.format
df_gains = df_rev_exp[((df_rev_exp.ltd_spending) < df_rev_exp.REV2)]
df_gains.tail()
# scatter plot of losses
import plotly.express as px
fig = px.scatter(df_gains, x="site_name",
y="gain_or_loss",
color="gain_or_loss",
size='REV2', hover_data=['site_name','REV2'])
fig.update_xaxes(tickangle=325)
fig.show()
Everything plots just fine but the REV2 is pretty large, and as such it is hard to read when I hover over the data points in the chart. I'm trying to figure out a way to show numbers as millions. For instance, In would like to see 1.25M and not 1257789.84, which is what I am seeing now. I tried playing around with fig.update but I couldn't get anything working. How can I modify the formatting on these plotly charts?
I'm on Plotly 4.14.3 and this version shows 2.2M straight out of the box when the source is x=[10000000, 22000000, 34000000]:
import numpy as np
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces(go.Scatter(x=[10*10**6, 22*10**6, 34*10**6],
y=[10,12,14]))
fig.show()
So two things come to mind:
Update Plotly.
Check that you're inputting your values as values and not strings

any workaround to customize plotly multiple time series in python (updated)?

I am trying to customize plotly iplot that rendered multiple time series, but iplot accept only one parameters. I checked into plotly documentation, and usinf go object was mentioned. But I am still not able able to adding custom fonts and watermark to the plotly plot. Can anyone help me out? any possible idea to make this work?
minimal data and demo code
Here is the code that I tried to use for adding custom fonts and watermark on that. I am new to plotly so some fancy built int functions are not quite intuitive to me. Any possible help would be appreciated.
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.core.display import display, HTML
import matplotlib as mpl
import cufflinks as cf
import seaborn as sns
import pandas as pd
import numpy as np
# setup
display(HTML("<style>.container { width:35% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
np.random.seed(1)
mpl.rcParams['figure.dpi']= 440
# sample data from cufflinks
df = cf.datagen.lines()
# plotly
iplot([{
'x': df.index,
'y': df[col],
'name': col
} for col in df.columns])
plus, I want to smooth the output of above code (which is multiple time series plot), how can I do that? any idea? Thanks
update
I have done this with matplotlib but don't know doing same thing in plotly. here is my script for loading customized font, watermark:
import matplotib.pyplot as plt
import matplotlib.font_manager as fm
fig, ax = plt.subplots(figsize=(10,6))
fname=r'C:\Users\Nunito-Black.ttf'
myfont=fm.FontProperties(fname=fname,size=50)
legend_fname=r'C:\Users\RobotoCondensed-Regular.ttf'
legend_font=fm.FontProperties(fname=legend_fname,size=20)
## some code for passing plot data to plotting function
ax.text(0.5, 0.5, 'mylogo',fontsize=60,fontproperties=myfont,color='black',
transform=ax.transAxes,ha='center', va='center', alpha=0.3)
plt.show()
how can I do same things in plotly plot? any idea?
Note: This is not (yet) an answer.
I do not understand what do you mean by smooth on the first part. Anyway I see some not necessary imports plus it seems to me you use plotly with an old sintax.
import plotly.graph_objs as go
import cufflinks as cf
import pandas as pd
df = cf.datagen.lines()
fig = go.Figure()
for col in df.columns:
fig.add_trace(
go.Scatter(x=df.index,
y=df[col],
name=col))
fig.show()
The output being
Consider that in this case you could use pd.util.testing.makeTimeDataFrame() instead of import cufflinks.
For the second part i suggest you to read the documentation for go.Layout.font? which is
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The plotly service (at https://plot.ly
or on-premise) generates images on a server,
where only a select number of fonts are
installed and supported. These include "Arial",
"Balto", "Courier New", "Droid Sans",, "Droid
Serif", "Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size
The usage in Python is here and apparently the js version is more flexible see this

Programmatically making and saving plots in (I)python without rendering them on the screen first

Here's a dummy script that makes three plots and saves them to PDF.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
I'm using spyder, which uses IPython. When I run this script, three windows pop at me and then go away. It works, but it's a little annoying.
How can I make the figures get saved to pdf without ever being rendered on my screen?
I'm looking for something like R's
pdf("path/to/plot/name.pdf")
commands
dev.off()
inasmuch as nothing gets rendered on the screen, but the pdf gets saved.
Aha. Partially based on the duplicate suggestion (which wasn't exactly a duplicate), this works:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
import matplotlib
old_backend = matplotlib.get_backend()
matplotlib.use("pdf")
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
matplotlib.use(old_backend)
Basically, set the backend to something like a pdf device, and then set it back to whatever you're accustomed to.
I am referring you to this StackOverflow answer which cites this article as an answer. In the SO answer they also suggest plt.ioff() but are concerned that it could disable other functionality should you want it.

unwanted blank subplots in matplotlib

I am new to matplotlib and seaborn and is currently trying to practice the two libraries using the classic titanic dataset. This might be elementary, but I'm trying to plot two factorplots side by side by inputting the argument ax = matplotlib axis as shown in the code below:
import matploblib.pyplot as plt
import seaborn as sns
%matplotlib inline
fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='Pclass',data=titanic_df,kind='count',hue='Survived',ax=axis1)
sns.factorplot(x='SibSp',data=titanic_df,kind='count',hue='Survived',ax=axis2)
I was expecting the two factorplots side by side, but instead of just that, I ended up with two extra blank subplots as shown above
Edited: image was not there
Any call to sns.factorplot() actually creates a new figure, although the contents are drawn to the existing axes (axes1, axes2). Those figures are shown together with the original fig.
I guess the easiest way to prevent those unused figures from showing up is to close them, using plt.close(<figure number>).
Here is a solution for a notebook
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline
titanic_df = pd.read_csv(r"https://github.com/pcsanwald/kaggle-titanic/raw/master/train.csv")
fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='pclass',data=titanic_df,kind='count',hue='survived',ax=axis1)
sns.factorplot(x='sibsp',data=titanic_df,kind='count',hue='survived',ax=axis2)
plt.close(2)
plt.close(3)
(For normal console plotting, remove the %matplotlib inline command and add plt.show() at the end.)

Categories

Resources