我是新来的。我试图在图中创建一个计数图。我正在读取一个数据框,这是我在数据框中的列和值。
名称缺陷严重程度
User1中
User1中
User1高
User2高
这就是我希望显示最终图形的方式
有人可以建议我如何在Plotly中进行编码吗?
答案 0 :(得分:1)
借助 pandas groupby
和 plotly 的 barmode
属性,您可以使用两行代码来完成。
Plotly 的条形图有一个特定的属性来控制如何显示条形,它被称为 barmode
,引用 API 文档:
barmode: str (默认 'relative'
)
'group'
、'overlay'
或 'relative'
之一在 'relative'
模式下,
对于正值,条形堆叠在零以上,对于
负值。在 'overlay'
模式下,条形图绘制在一个
其他。在 'group'
模式下,条形并排放置。
有关示例,请参阅 bar chart documentation。
现在,以您的示例为例:
# import needed libraries
import pandas as pd
import plotly.express as px
# some dummy dataset
df = pd.DataFrame(
{
"Name": ["User1", "User1", "User1", "User2"],
"Defect severity": ["Medium", "Medium", "High", "High"],
}
)
您需要按 Name
和 Defect severity
列进行分组,然后使用 count
聚合函数(我建议您查看此 question)>
df = df.groupby(by=["Name", "Defect severity"]).size().reset_index(name="counts")
现在的数据将如下所示:
姓名 | 缺陷严重程度 | 计数 | |
---|---|---|---|
0 | User1 | 高 | 1 |
1 | User1 | 中 | 2 |
2 | User2 | 高 | 1 |
最后,您可以使用 plotly 条形图:
px.bar(data_frame=df, x="Name", y="counts", color="Defect severity", barmode="group")
图表为:
你去吧!只用两行代码,你就得到了一个漂亮的分组条形图。
答案 1 :(得分:0)
我几乎创建了您想要的所有内容。不幸的是,我没有找到正确设置图例标题的方法(annotations
不是设置图例标题的好参数)。要显示数字(1.0,2.0),必须创建一个带有值(列-df["Severity numbers"]
)的附加列。
代码:
# import all the necessaries libraries
import pandas as pd
import plotly
import plotly.graph_objs as go
# Create DataFrame
df = pd.DataFrame({"Name":["User1","User1", "User1","User2"],
"Defect severity":["Medium","Medium","High","High"],
"Severity numbers":[1,1,2,2]})
# Create two additional DataFrames to traces
df1 = df[df["Defect severity"] == "Medium"]
df2 = df[df["Defect severity"] == "High"]
# Create two traces, first "Medium" and second "High"
trace1 = go.Bar(x=df1["Name"], y=df1["Severity numbers"], name="Medium")
trace2 = go.Bar(x=df2["Name"], y=df2["Severity numbers"], name="High")
# Fill out data with our traces
data = [trace1, trace2]
# Create layout and specify title, legend and so on
layout = go.Layout(title="Severity",
xaxis=dict(title="Name"),
yaxis=dict(title="Count of defect severity"),
legend=dict(x=1.0, y=0.5),
# Here annotations need to create legend title
annotations=[
dict(
x=1.05,
y=0.55,
xref="paper",
yref="paper",
text=" Defect severity",
showarrow=False
)],
barmode="group")
# Create figure with all prepared data for plot
fig = go.Figure(data=data, layout=layout)
# Create a plot in your Python script directory with name "bar-chart.html"
plotly.offline.plot(fig, filename="bar-chart.html")
答案 2 :(得分:0)
data = [
go.Bar(
y=coach_sectors['Sectors'].value_counts().to_dense().keys(),
x=coach_sectors['Sectors'].value_counts(),
orientation='h',
text="d",
)]
layout = go.Layout(
height=500,
title='Sector/ Area of Coaches - Combined',
hovermode='closest',
xaxis=dict(title='Votes', ticklen=5, zeroline=False, gridwidth=2, domain=[0.1, 1]),
yaxis=dict(title='', ticklen=5, gridwidth=2),
showlegend=False
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='Sector/ Area of Coaches - Combined')