Plotly饼图和标签顺序

9
如何更改饼图(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()

给出这个图表: 图表
4个回答

15

有两件事情:

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
对于在React(JavaScript)中有同样问题的人,可以将sort: false添加到您的Plot组件的data属性中:
const data = [{
    values: myValues,
    labels: myLabels,
    sort: false
}];

return (
    <Plot data={data} />
)

1
图例的顺序将与标签中的顺序对应(除非在默认情况下为True的图表中, sort = 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()

1

使用 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".

在官方文档中查看更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接