python - Plotly subplot 不喜欢循环条形图?
问题描述
我正在尝试创建一个包含一个条形图和一个数据表的子图的简单 pdf:
Bar and table 函数有效,但是当我尝试创建子图时,会出现以下错误:
ValueError:
Invalid element(s) received for the 'data' property of
Invalid elements include
我写了以下内容: 难道我不喜欢我循环酒吧的痕迹吗?
我首先创建函数来构建条形图和数据表:
import plotly
import plotly.graph_objects as go
import plotly.figure_factory as ff
import os
import numpy as np
from plotly.subplots import make_subplots
import pandas as pd
def build_barchart(df,columns):
x = df.City.unique() # City column should always be the x axis
fig = go.Figure()
fig.update_layout(barmode='stack')
for column in columns:
Y=df[column].tolist()
fig.add_trace(go.Bar(name=column,x=x,y=Y))
return fig
def build_table(df):
table = ff.create_table(df)
return table
def create_pdf(df,columns):
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
build_barchart(df,columns),
row=1, col=1
)
fig.add_trace(
build_table(df),
row=1, col=2
)
if not os.path.exists("images"):
os.mkdir("images")
fig.write_image("images/fig1.pdf")
return
创建构建功能后,我尝试使用它们......
df = pd.read_csv('DATA.csv', delimiter=';')
columns=['%Something','%Dogs','%Cats','%Cars']
table = build_table(df)
bars = build_barchart(df,columns)
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
bars,
row=1, col=1
)
fig.add_trace(
table,
row=1, col=2
)
fig.show()
测试数据
City;%Something;%Dogs;%Cats;%Cars;Nr Alarms;Nr Block
USA;60;10;5;25;1;1
CANADA;20;10;5;65;2;2
MEXICO;90;5;5;0;3;3
SWEDEN;10;10;5;75;4;4
解决方案
请不要把它当作答案。鉴于您的代码有一些缺陷,我正在添加一个完善的版本。特别是如果您有重复的国家/x = df.City.astype('str').unique()
地区无法正常工作Y
,您应该在绘制之前安排/检查您的数据。
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
df = pd.DataFrame({
'City': {0: 'USA', 1: 'CANADA', 2: 'MEXICO', 3: 'SWEDEN'},
'%Something': {0: 60, 1: 20, 2: 90, 3: 10},
'%Dogs': {0: 10, 1: 10, 2: 5, 3: 10},
'%Cats': {0: 5, 1: 5, 2: 5, 3: 5},
'%Cars': {0: 25, 1: 65, 2: 0, 3: 75},
'Nr Alarms': {0: 1, 1: 2, 2: 3, 3: 4},
'Nr Block': {0: 1, 1: 2, 2: 3, 3: 4}})
def build_subplot(df, columns=None):
if columns is None:
columns = df.columns
# only columns starting with %
columns = [col for col in columns if col.startswith("%")]
fig = make_subplots(rows=1, cols=2,
specs=[
[{"type": "bar"},{"type": "table"}]
]
)
fig.update_layout(barmode='stack')
for column in columns:
fig.append_trace(
go.Bar(x=df["City"],
y=df[column],
name=column),
row=1,col=1)
fig.add_trace(
go.Table(
header=dict(
values=df.columns,
font=dict(size=10),
align="left"
),
cells=dict(
values=df.T.values.tolist(),
align = "left")
),
row=1, col=2
)
return fig
build_subplot(df, ['%Something', '%Dogs', 'Nr Block'])
附录:我认为如果你的子图有 1 列和 2 行会更好看,因为表格中的一些细节可能难以阅读。
推荐阅读
- jquery - 如何将多个下拉值作为 URL 参数传递?
- geb - 如果不接受等待,则可以重新加载页面
- javascript - Photoshop JSX 裁剪:文件太大
- python - 数据标准化 vs 标准化 vs 强大的缩放器
- arrays - 在反应中映射对象键并返回子属性
- javascript - 如何使用 javascript/jQuery 在浏览器中创建页面位置?
- c# - 下载 Excel 文件后,Bootstrap 模式不会隐藏
- apache - htaccess 重定向到相同(未知)子文件夹中的 index.html
- c++ - 如何使用 Qt 减少小部件和窗口大小之间的距离?
- java - 使用 jbutton 从 jtable 中删除一行