如何在plotly3.6中对条形图进行排序?

时间:2019-08-26 15:57:52

标签: python plotly

我的办公计算机中安装了plotly3.6,无法升级。 而且我试图绘制排序的条形图,但是这样做没有成功。

我该怎么办?

我的尝试

def barplot(x,y):
    data = [go.Bar(
        x=x,
        y=y,
        marker={
            'color': y,
            'colorscale': 'Reds'
        }
    )]

    layout = {
        'xaxis': {
            'tickvals': x,
            'ticktext': [str(i) for i in x],
            'tickangle': 40,
            'type': "category",
            'categoryorder': 'category ascending'
        }
    }

    fig = go.FigureWidget(data=data, layout=layout)

    return iplot(fig)


# plot
x = list('abcde')
y = [20,10,5,8,9]


barplot(x,y)

相关链接: (这仅适用于plotly3.10,不适用于3.6) How to plot sorted barplot in plolty3.10

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是执行此操作的函数的版本...基本上,您只是对传递到x中的ygo.Bar()值进行了预排序。因为在这种情况下,x是字符串列表,所以推断xaxis.type"category",并且类别的顺序默认为x列表的顺序是提供的,因此无需摆弄tickvalsticktext

import plotly.graph_objs as go
from plotly.offline import iplot

def barplot(x,y):
    sorted_y = sorted(y)
    sorted_x = [str(j) for i,j in sorted(zip(y,x))]

    data = [go.Bar(
        x=sorted_x,
        y=sorted_y,
        marker={
            'color': y,
            'colorscale': 'Reds'
        }
    )]

    fig = go.FigureWidget(data=data)

    return iplot(fig)


# plot
x = list('abcde')
y = [20,10,5,8,9]


barplot(x,y)