Build slice by slice a heatmap in Plotly - python

I am trying to build slice by slice a heatmap. How can I update the data present in the graph without generating a full figure? The following code each time produces a new plot. I tried to use fig.update_traces() but it didn’t work.
What am I missing?
Thanks
import plotly.express as px
import pandas as pd
import time
df = pd.DataFrame(np.random.rand(1,100))
for i in range(0,10):
df = df.append(pd.DataFrame(np.random.rand(1,100)), ignore_index = True)
time.sleep(1)
fig = px.imshow(df)
fig.show()

Related

How can i make this time series graph interactive?

I am new to Python and Pandas so any help is much appreciated.
I am trying to make the graph below interactive, it would also be good to be able to choose which attributes show rather than them all.
Here is what I have so far
df.set_index('Current Year').plot(rot=45)
plt.xlabel("Year",size=16)
plt.ylabel("",size=16)
plt.title("Current year time series plot", size=18)
I know that i need to import the following import plotly.graph_objects as go but no idea how to implement this with the above time series graph. Thanks
EDIT
I am getting this error when trying to enter my plotted data.
All you need is:
df.plot()
As long as you import the correct libraries and set plotly as the plotting backend for pandas like this:
import pandas as pd
pd.options.plotting.backend = "plotly"
df = pd.DataFrame({'year':['2020','2021','2022'], 'value':[1,3,2]}).set_index('year')
fig = df.plot(title = "Current year time series plot")
fig.show()
Plot:
Complete code:
import pandas as pd
pd.options.plotting.backend = "plotly"
df = pd.DataFrame({'year':['2020','2021','2022'], 'value':[1,3,2]}).set_index('year')
fig = df.plot(title = "Current year time series plot")
fig.show()

Fastest way to parse multiple header names to Plotly (Python

so I've been experimenting with plotly and trying to get plotting multiple traces. I wrote the following code which plots two traces on the same graph :
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
data = pd.read_csv("data.csv")
headers = pd.read_csv("data.csv", index_col=0, nrows=0).columns.tolist()
fig = go.Figure()
fig = px.line(data, x="DateTime", y=[headers[0], headers[1]])
fig.show()
In this example the first and second headers are plotted as traces on the graph. I was wondering if there was a way other than y=[headers[n],headers[n+1]]... to get all the lines drawn on? I tried just using the headers array without an index, but it gives a ValueError
Plotly Express cannot process wide-form data with columns of different type.
So, is there a plotly-specific way to make this more efficient & readable than just writing every index in the plot header definition, or can it be done with standard python?
EDIT: the actual data sample is a csv providing int values with a header and date :
DateTime X Y Z
01-JAN-2018,5,6,7...
02-JAN-2018,7,8,9
if your sample data is what is in your CSV, it's a simple case of defining y as the numeric columns
import io
import pandas as pd
import plotly.express as px
headers = pd.read_csv(io.StringIO("""DateTime,X,Y,Z
01-JAN-2018,5,6,7
02-JAN-2018,7,8,9
"""))
px.line(headers, x="DateTime", y=headers.select_dtypes("number").columns)

Plotly bar chart not ascending/descending

I have a bar chart in plotly that I have produced, however, it is not in any type of order. How would I sort to ascending or descending?
What I am doing:
fig = px.bar(data, x='Old_SKU', y='u_power')
fig = data.sort_values('u_power', ascending=True)
fig.show()
I'm not sure what your desired output is, or what your data looks like. In any case fig in plotly terms is normaly a plotly figure object. When you're running fig = data.sort_values('u_power', ascending=True) you're not building a figure, but sorting a dataframe. So far I can only imagine that you'd like to sort a dataset that looks like this:
... into this:
Or maybe you're expecting a continuous increase or decrease? In that case you will have to share a dataset. Nevertheless, with a few tweaks depending on your dataset, the following snippet should not be far from a working solution:
import plotly.express as px
import numpy as np
import pandas as pd
var = np.random.randint(low=2, high=6, size=20).tolist()
data = pd.DataFrame({'u_power':var,
'Old_SKU':np.arange(0, len(var))})
# fig = px.bar(data, x='Old_SKU', y='u_power', barmode='stack')
fig = px.bar(data.sort_values('u_power'), x='Old_SKU', y='u_power', barmode='stack')
fig.show()

Plotly Animated Bar Graph Showing 1 subgroup only in Jupyter

Issue: When I run my code only one status (sub group) shows. The data set is very simple, create date, status and count. I can only think something might be wrong with my data set at this point. Why will it only show one status of the three I have or possibly it works better with a hosted file? It seems to just iterate through the list and not keep each data point in tact until the end. The other code block works fine on github.
Sample of my data set:
Status,Create Date,Count
None,17-Apr-12,8
None,30-Apr-12,9
None,23-Aug-12,10
None,3-Oct-12,11
None,9-Jan-13,12
None,29-Jan-13,13
QBOS,31-Jan-13,1
QBDS,1-Feb-13,1
My code:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
df = pd.read_csv('qb7.csv')
df.columns = ['Status','Create Date','Count']
includes=['None','QBDS', 'QBOS']
df=df[df['Status'].isin(includes)]
df['Create Date']= pd.to_datetime(df['Create Date']).dt.strftime('%Y-%m-%d')
fig = px.bar(df,
x="Status",
y="Count",
color="Status",
animation_frame="Create Date", hover_name="Status",
range_y=[0,8000])
fig.show()
``
Sample of what I want to make:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
df = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-
confirmed-cases-of-covid-19-tests-per-case.csv')
df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']
includes=['United States','Russia', 'India','Brazil']
df=df[df['Country'].isin(includes)]
df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')
fig = px.bar(df, x="Country", y="Confirmed", color="Country",
animation_frame="Date", animation_group="Country", range_y=[0,35000])
fig.show()`
I think the reason it doesn't show the intended graph is because of the different number of data. The intended result is achieved when the number of data is aligned.
import pandas as pd
import numpy as np
import io
data = '''
Status,Create Date,Count
None,17-Apr-12,8
None,30-Apr-12,9
None,23-Aug-12,10
None,3-Oct-12,11
None,9-Jan-13,12
None,29-Jan-13,13
QBOS,17-Apr-12,8
QBOS,30-Apr-12,9
QBOS,23-Aug-12,10
QBOS,3-Oct-12,11
QBOS,9-Jan-13,12
QBOS,29-Jan-13,13
QBDS,17-Apr-12,8
QBDS,30-Apr-12,9
QBDS,23-Aug-12,10
QBDS,3-Oct-12,11
QBDS,9-Jan-13,12
QBDS,29-Jan-13,13
'''
df = pd.read_csv(io.StringIO(data), sep=',')
import plotly.graph_objects as go
import plotly.express as px
# df = pd.read_csv('qb7.csv')
df.columns = ['Status','Create Date','Count']
includes=['None','QBDS', 'QBOS']
df=df[df['Status'].isin(includes)]
df['Create Date']= pd.to_datetime(df['Create Date']).dt.strftime('%Y-%m-%d')
fig = px.bar(df,
x="Status",
y="Count",
color="Status",
animation_frame="Create Date", hover_name="Status",
range_y=[0,30])
fig.show()

Plotly: How to add vertical lines at specified points?

I have a data frame plot of a time series along with a list of numeric values at which I'd like to draw vertical lines. The plot is an interactive one created using the cufflinks package. Here is an example of three time series in 1000 time values, I'd like to draw vertical lines at 500 and 800. My attempt using "axvlinee" is based upon suggestions I've seen for similar posts:
import numpy as np
import pandas as pd
import cufflinks
np.random.seed(123)
X = np.random.randn(1000,3)
df=pd.DataFrame(X, columns=['a','b','c'])
fig=df.iplot(asFigure=True,xTitle='time',yTitle='values',title='Time Series Plot')
fig.axvline([500,800], linewidth=5,color="black", linestyle="--")
fig.show()
The error message states 'Figure' object has no attribute 'axvline'.
I'm not sure whether this message is due to my lack of understanding about basic plots or stems from a limitation of using igraph.
The answer:
To add a line to an existing plotly figure, just use:
fig.add_shape(type='line',...)
The details:
I gather this is the post you've seen since you're mixing in matplotlib. And as it has been stated in the comments, axvline has got nothing to do with plotly. That was only used as an example for how you could have done it using matplotlib. Using plotly, I'd either go for fig.add_shape(go.layout.Shape(type="line"). But before you try it out for yourself, please b aware that cufflinks has been deprecated. I really liked cufflinks, but now there are better options for building both quick and detailed graphs. If you'd like to stick to one-liners similat to iplot, I'd suggest using plotly.express. The only hurdle in your case is changing your dataset from a wide to a long format that is preferred by plotly.express. The snippet below does just that to produce the following plot:
Code:
import numpy as np
import pandas as pd
import plotly.express as px
from plotly.offline import iplot
#
np.random.seed(123)
X = np.random.randn(1000,3)
df=pd.DataFrame(X, columns=['a','b','c'])
df['id'] = df.index
df = pd.melt(df, id_vars='id', value_vars=df.columns[:-1])
# plotly line figure
fig = px.line(df, x='id', y='value', color='variable')
# lines to add, specified by x-position
lines = {'a':500,'c':700,'a':900,'b':950}
# add lines using absolute references
for k in lines.keys():
#print(k)
fig.add_shape(type='line',
yref="y",
xref="x",
x0=lines[k],
y0=df['value'].min()*1.2,
x1=lines[k],
y1=df['value'].max()*1.2,
line=dict(color='black', width=3))
fig.add_annotation(
x=lines[k],
y=1.06,
yref='paper',
showarrow=False,
text=k)
fig.show()
Not sure if this is what you want, adding two scatter seems to work:
np.random.seed(123)
X = np.random.randn(1000,3)
df=pd.DataFrame(X, columns=['a','b','c'])
fig = df.iplot(asFigure=True,xTitle='time',yTitle='values',title='Time Series Plot')
fig.add_scatter(x=[500]*100, y=np.linspace(-4,4,100), name='lower')
fig.add_scatter(x=[800]*100, y=np.linspace(-4,4,100), name='upper')
fig.show()
Output:

Categories