[英]Plotly: How to create subplots from each column in a pandas dataframe?
我有一个包含 36 列的 dataframe 'df',这些列被绘制到一个 plotly 图表上,并使用下面的代码以 html 格式显示。
import plotly.offline as py
import plotly.io as pio
pio.write_html(py.offline.plot([{
'x': df.index,
'y': df[col],
'name': col
}for col in trend_data.columns], filename=new_file_path))
我想遍历每一列并为每一列创建一个子图。 我努力了;
from plotly.subplots import make_subplots
sub_titles = df.columns()
fig = make_subplots(rows=6, cols=6, start_cell="bottom-left", subplot_titles=sub_titles)
for i in df.columns:
fig.add_trace(i)
我创建了 6 行和列,因为这将提供 36 个图,并尝试使用 header 名称作为子图标题,但我收到一个 ValueError ,说明它需要一个二维字典列表。
另外,我尝试通过以下方式添加子图标题;
sub_titles = list(df)
fig = py.subplots.make_subplots(rows=6, cols=6, sub_titles=sub_titles)
这也会返回错误。 任何帮助表示赞赏。
Plot:
代码:
# imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# data
np.random.seed(123)
frame_rows = 50
n_plots = 36
frame_columns = ['V_'+str(e) for e in list(range(n_plots+1))]
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
index=pd.date_range('1/1/2020', periods=frame_rows),
columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100
# plotly setup
plot_rows=6
plot_cols=6
fig = make_subplots(rows=plot_rows, cols=plot_cols)
# add traces
x = 0
for i in range(1, plot_rows + 1):
for j in range(1, plot_cols + 1):
#print(str(i)+ ', ' + str(j))
fig.add_trace(go.Scatter(x=df.index, y=df[df.columns[x]].values,
name = df.columns[x],
mode = 'lines'),
row=i,
col=j)
x=x+1
# Format and show fig
fig.update_layout(height=1200, width=1200)
fig.show()
加法: 1列溶液:
代码:
# imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# data
np.random.seed(123)
frame_rows = 50
frame_columns = ['V_'+str(e) for e in list(range(1,37))]
df = pd.DataFrame(np.random.uniform(-8,10,size=(frame_rows, len(frame_columns))),
index=pd.date_range('1/1/2020', periods=frame_rows),
columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100
# plotly setup
plot_rows=6
plot_cols=6
lst1 = list(range(1,plot_rows+1))
lst2 = list(range(1,plot_cols+1))
fig = make_subplots(rows=36, cols=1, subplot_titles=df.columns, insets=[{'l': 0.1, 'b': 0.1, 'h':1}])
# add traces
x = 1
for i in lst1:
for j in lst2:
#print(str(i)+ ', ' + str(j))
fig.add_trace(go.Scatter(x=df.index, y=df[df.columns[x-1]].values,
name = df.columns[x-1],
mode = 'lines',
),
row=x,
col=1)
x=x+1
fig.update_layout(height=12000, width=1200)
fig.show()
情节:
请参阅有关如何使用子图的文档。 这可以工作:
更新包括子情节标题
fig = py.subplots.make_subplots(rows=36, cols=1, subplot_titles=df.columns)
j = 1
for i in df.columns:
fig.add_trace(
go.Scatter(
{'x': df.index,
'y': df[i]}),
row=j, col=1)
j += 1
这导致以下 plot (我的数据):
df = pd.DataFrame(np.random.randint(5, size=(5, 3)), columns=['one', 'two', 'three'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.