绘制饼图和标签顺序

时间:2019-08-17 17:47:22

标签: python plotly

如何更改(饼图)饼图中的标签顺序?

我要强制执行以下命令:20 16 15

而不是16 15 20


我的csv文件:

id,A,B,C
1,15,16,45
2,20,15,54
3,16,18,60
4,16,15,54
5,15,12,68
6,16,20,68

我的python代码

import pandas
import plotly.graph_objects as go

col_label = "A"
col_values = "Count"

data = pandas.read_csv(mycsvfile)
v = data[col_label].value_counts()
new = pandas.DataFrame({
    col_label: v.index,
    col_values: v.values
})
fig = go.Figure(
    data=[go.Pie(
        labels=new[col_label],
        values=new[col_values])
    ])
fig.show()

给出此图: graph

3 个答案:

答案 0 :(得分:3)

有两件事:

import pandas
import plotly.graph_objects as go

col_label = "A"
col_values = "Count"

data = pandas.read_csv("mycsvfile")
v = data[col_label].value_counts()
new = pandas.DataFrame({
    col_label: v.index,
    col_values: v.values
})
# First, make sure that the data is in the order you want it to be prior to plotting 
new = new.sort_values(
  by=col_label, 
  ascending=False)

fig = go.Figure(
    data=[go.Pie(
        labels=new[col_label],
        values=new[col_values],
        # Second, make sure that Plotly won't reorder your data while plotting
        sort=False)
    ])
fig.write_html('first_figure.html', auto_open=False)

有关有效的演示,请参见此Repl.it(它会生成带有绘图的html页面)。

答案 1 :(得分:1)

图例顺序将与标签中的顺序相对应(除非图表中的sort = True默认为True)。您要做的是按照降序对'A'值进行排序,然后创建带有添加参数sort=False

的图
import pandas
import plotly.graph_objects as go

col_label = "A"
col_values = "B"

data = pandas.read_csv(mycsvfile)
v = data[col_label].value_counts()
new = pandas.DataFrame({
    col_label: v.index,
    col_values: v.values
})
new = new.sort_values('A', ascending=False)

fig = go.Figure(
    data=[go.Pie(
        labels=new[col_label],
        values=new[col_values],
        sort=False
        )
    ])
fig.show()

答案 2 :(得分:0)

使用layout.legend.traceorder属性,例如:

traceorder (flaglist string) 

Any combination of "reversed", "grouped" joined with a "+" OR "normal". 
examples: "reversed", "grouped", "reversed+grouped", "normal" 
Determines the order at which the legend items are displayed. 

If "normal", the items are displayed top-to-bottom in the same order 
as the input data. If "reversed", the items are displayed in the opposite order 
as "normal". If "grouped", the items are displayed in groups (when a trace
`legendgroup` is provided).  If "grouped+reversed", the items are displayed in the 
opposite order as "grouped".

在官方documentation中查看更多信息。