Plotly: How to retrieve values for major ticks and gridlines? - python

I'd like to retrieve the x-values highlighted in this plot:
The plot is generated in a Jupyter Notebook using this snippet:
import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np
# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')
# Random data using cufflinks
df = cf.datagen.lines()
# plot
fig = df.iplot(asFigure=True, kind='scatter',xTitle='Dates',yTitle='Returns',title='Returns')
iplot(fig)
This is what I've tried:
With this setup, you can retrieve every x and y value for every series by simply running fig in the notebook. But the tick values are nowhere to be found.
I'v also tried digging deeper in dir(fig), and thought maybe the output from fig.axis would do the trick, but no:
{'x1': {'gridcolor': '#E1E5ED',
'showgrid': True,
'tickfont': {'color': '#4D5663'},
'title': {'text': 'Dates', 'font': {'color': '#4D5663'}},
'zerolinecolor': '#E1E5ED'},
'y1': {'gridcolor': '#E1E5ED',
'showgrid': True,
'tickfont': {'color': '#4D5663'},
'title': {'text': 'Returns', 'font': {'color': '#4D5663'}},
'zerolinecolor': '#E1E5ED'}}
There are however other options for the grid and ticks there like 'showgrid': True, and 'tickfont', but the values seem to be "hidden" somewhere else.
Any suggestions?

This data is only available in the Javascript context, and so unfortunately is inaccessible from Python.

Related

rather than directly plotting ,need to plot smooth line chart python

i have a 3 df's fro 3 machines(Machine1/Machine2/Machine3) .Each df with 3 columns. Day-shift and production.
sample df:
Day-Shift Production Quality
Day 11-01 20 A
Night 11-01 45 A
Day 11-02 65 A
Night 11-02 12 B
Day 11-03 97 B
my code:
import numpy as np
import pandas as pd
from plotly.offline import iplot
import plotly.graph_objects as go
# Machine1: Create numpy arrays of values for the given quality.
b1 = np.where(df1['Quality'] == 'A', df1['Production'], None)
# Machine2: Same as above.
b2 = np.where(df2['Quality'] == 'A', df2['Production'], None)
# Machine3: Same as above.
b3 = np.where(df3['Quality'] == 'A', df3['Production'], None)
# Setup.
t = []
line = ['solid']
Quality = ['A']
t.append({'x': df1['Day-Shift'],
'y': b1,
'name': f'Machine1',
'line': {'color': 'red',
'dash': line[0]}})
t.append({'x': df2['Day-Shift'],
'y': b2,
'name': f'Machine1',
'line': {'color': 'blue',
'dash': line[0]}})
t.append({'x': df3['Day-Shift'],
'y': b3,
'name': f'Machine1',
'line': {'color': 'yellow',
'dash': line[0]}})
# Plot the graph.
layout = go.Layout(
title='Production meterage of Machine1/Machine2/Machine3 for Quality A',
template='plotly_dark',
xaxis=dict(
autorange=True
),
yaxis=dict(
autorange=True
)
)
fig = go.Figure(data=t, layout=layout)
iplot(fig)
Chart I got:
I created one line chart for all three machines. But the line chart looks messy. Need to do smoothing. I tried with gaussian_filter1d. But It does not work for me.
I think the best way of representing your data is with a histogram. I don't know much of ploty ofline module but you can do it (easily) with matplotlib.
Here is some documentation from matplotlib
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html
and an example:
https://matplotlib.org/3.1.1/gallery/statistics/hist.html
and an example with multiply datasets for 1 chart
https://matplotlib.org/3.1.1/gallery/statistics/histogram_multihist.html

Plotly: Change y-axis scale

I have a dataset that looks like this:
x y z
0 Jan 28446000 110489.0
1 Feb 43267700 227900.0
When I plot a line chart like this:
px.line(data,x = 'x', y = ['y','z'], line_shape = 'spline', title="My Chart")
The y axis scale comes from 0 to 90 M. The first line on the chart for y is good enough. However, the second line appears to be always at 0M. What can I do to improve my chart such that we can see clearly how the values of both column change over the x values?
Is there any way I can normalize the data? Or perhaps I could change the scaling of the chart.
Often times we use data which is in different scales, and scaling the data would mask a characteristic we wish to display. One way to handle this is to add a secondary y-axis. An example is shown below.
Key points:
Create a layout dictionary object
Add a yaxis2 key to the dict, with the following: 'side': 'right', 'overlaying': 'y1'
This tells Plotly to create a secondary y-axis on the right side of the graph, and to overlay the primary y-axis.
Assign the appropriate trace to the newly created secondary y-axis as: 'yaxis': 'y2'
The other trace does not need to be assigned, as 'y1' is the default y-axis.
Comments (TL;DR):
The example code shown here uses the lower-level Plotly API, rather than a convenience wrapper such as graph_object to express. The reason is that I (personally) feel it's helpful to users to show what is occurring 'under the hood', rather than masking the underlying code logic with a convenience wrapper.
This way, when the user needs to modify a finer detail of the graph, they will have a better understanding of the lists and dicts which Plotly is constructing for the underlying graphing engine (orca).
The Docs:
Here is a link to the Plotly docs referencing multiple axes.
Example Code:
import pandas as pd
from plotly.offline import iplot
df = pd.DataFrame({'x': ['Jan', 'Feb'],
'y': [28446000, 43267700],
'z': [110489.0, 227900.0]})
layout = {'title': 'Secondary Y-Axis Demonstration',
'legend': {'orientation': 'h'}}
traces = []
traces.append({'x': df['x'], 'y': df['y'], 'name': 'Y Values'})
traces.append({'x': df['x'], 'y': df['z'], 'name': 'Z Values', 'yaxis': 'y2'})
# Add config common to all traces.
for t in traces:
t.update({'line': {'shape': 'spline'}})
layout['yaxis1'] = {'title': 'Y Values', 'range': [0, 50000000]}
layout['yaxis2'] = {'title': 'Z Values', 'side': 'right', 'overlaying': 'y1', 'range': [0, 400000]}
iplot({'data': traces, 'layout': layout})
Graph:

Plotly: How to show legend in single-trace scatterplot with plotly express?

Sorry beforehand for the long post. I'm new to python and to plotly, so please bear with me.
I'm trying to make a scatterplot with a trendline to show me the legend of the plot including the regression parameters but for some reason I can't understand why px.scatter doesn't show me the legend of my trace. Here is my code
fig1 = px.scatter(data_frame = dataframe,
x="xdata",
y="ydata",
trendline = 'ols')
fig1.layout.showlegend = True
fig1.show()
This displays the scatterplot and the trendline, but no legend even when I tried to override it.
I used pio.write_json(fig1, "fig1.plotly") to export it to jupyterlab plotly chart studio and add manually the legend, but even though I enabled it, it won't show either in the chart studio.
I printed the variable with print(fig1) to see what's happening, this is (part of) the result
(Scatter({
'hovertemplate': '%co=%{x}<br>RPM=%{y}<extra></extra>',
'legendgroup': '',
'marker': {'color': '#636efa', 'symbol': 'circle'},
'mode': 'markers',
'name': '',
'showlegend': False,
'x': array([*** some x data ***]),
'xaxis': 'x',
'y': array([*** some y data ***]),
'yaxis': 'y'
}), Scatter({
'hovertemplate': ('<b>OLS trendline</b><br>RPM = ' ... ' <b>(trend)</b><extra></extra>'),
'legendgroup': '',
'marker': {'color': '#636efa', 'symbol': 'circle'},
'mode': 'lines',
'name': '',
'showlegend': False,
'x': array([*** some x data ***]),
'xaxis': 'x',
'y': array([ *** some y data ***]),
'yaxis': 'y'
}))
As we can see, creating a figure with px.scatter by default hides the legend when there's a single trace (I experimented adding a color property to px.scatter and it showed the legend), and searching the px.scatter documentation I can't find something related to override the legend setting.
I went back to the exported file (fig1.plotly.json) and manually changed the showlegend entries to True and then I could see the legend in the chart studio, but there has to be some way to do it directly from the command.
Here's the question:
Does anyone know a way to customize px.express graphic objects?
Another workaround I see is to use low level plotly graph object creation, but then I don't know how to add a trendline.
Thank you again for reading through all of this.
You must specify that you'd like to display a legend and provide a legend name like this:
fig['data'][0]['showlegend']=True
fig['data'][0]['name']='Sepal length'
Plot:
Complete code:
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length",
trendline='ols',
trendline_color_override='red')
fig['data'][0]['showlegend']=True
fig['data'][0]['name']='Sepal length'
fig.show()
Complete code:

Change fontsize in holoviews or hvplot

How do I change fontsizes using holoviews or hvplot?
Here's a simple example of the plot I have:
# import libraries
import numpy as np
import pandas as pd
import holoviews as hv
import hvplot.pandas
hv.extension('bokeh', logo=False)
# create sample dataframe
df = pd.DataFrame({
'col1': np.random.normal(size=30),
'col2': np.random.normal(size=30),
})
# plot data with holoviews
my_plot = hv.Scatter(df, label='Scattering around')
1) You can change fontsizes by using .opts(fontsize={}) on your plot, like so:
# change fontsizes for different parts of plot
my_plot.opts(fontsize={
'title': 15,
'labels': 14,
'xticks': 10,
'yticks': 10,
})
2) With version >= 1.13 of holoviews you can scale all the fonts all at once and make legend, title, xticks larger with .opts(fontscale=1.5):
# make fonts all at once larger for your plot by the same scale
# here I've chosen fontscale=2, which makes all fonts 200% larger
my_plot.opts(fontscale=2)
3) If you would like to scale your fonts and you have a bokeh backend for your holoviews plot, you can do:
# scale fontsizes with 200%
my_plot.opts(fontsize={
'title': '200%',
'labels': '200%',
'ticks': '200%',
})
More info on all the possible parts of which you can change the fontsize can be found here: http://holoviews.org/user_guide/Customizing_Plots.html#Font-sizes

How can I add a single line to a scatter plot in plotly?

Consider the following MWE to draw a scatter plot using the python API to plotly:
import plotly.plotly as py
import plotly.graph_objs
import plotly.offline
plotly.offline.init_notebook_mode()
data = list(range(10))
trace = plotly.graph_objs.Scatter(
x=list(range(len(data))),
y=data
)
plotly.offline.iplot([trace])
What if I now want to add a (say) horizontal line to this plot?
I went through the documentation, for example the section on line and scatter and that on line charts, but none of the examples seem to cover how to overlay different plots, or simply draw straight lines and similar shapes.
A naive approach to do this is to just add the line as a second scatter plot, like the following:
import plotly.plotly as py
import plotly.graph_objs
import plotly.offline
plotly.offline.init_notebook_mode()
data = list(range(10))
trace = plotly.graph_objs.Scatter(
x=list(range(len(data))),
y=data
)
trace_line = plotly.graph_objs.Scatter(
x=list(range(len(data))),
y=[4] * len(data),
mode='lines'
)
plotly.offline.iplot([trace, trace_line])
This approach seems however to be suboptimal: aside for the verbosity required to add a single line, it also makes me manually "sample" the straight line, and it adds the line height to the tooltip on mouse hover.
Is there a better approach to achieve this?
Hi from your question I can see that you need plotly shapes functionality and generate a horizontal line for the plot.
Please find below the code for doing the same graph you have shown in the question
Code:
from plotly.offline import iplot
import plotly.graph_objs as go
data = list(range(10))
trace = go.Scatter(
x=list(range(len(data))),
y=data
)
layout = {
'shapes': [
# Line Horizontal
{
'type': 'line',
'x0': 0,
'y0': 4,
'x1': 10,
'y1': 4,
'line': {
'color': 'rgb(50, 171, 96)',
'width': 4
},
}
],
'showlegend': True
}
fig = {
'data': [trace],
'layout': layout,
}
iplot(fig)
Output:
Additional reference:
plotly shapes examples
plotly shapes reference
Alternatively, you could use the add_shape method, see the doc here. If you add the following code, you could add the line same as y=4 as above.
fig.add_shape(type="line",
x0=4,
y0=0,
x1=4,
y1=10)
You can just add the next line:
fig.add_hline(y=4, line_width=2, line_dash='dash')
Also checkout the documentation for further deep into the features that plotly recently has added.

Categories

Resources