Plotly deactivate x axis sorting

安稳与你 提交于 2020-01-15 05:23:08

问题


I want to plot a bar chart. On the x-axis are IDs of consultants. They range between 1000 and 2000. Each consultant has a specific number of customers (y-axis).

Now I want to plot a bar chart in plotly. But plotly orders the consultant IDs ascending and interprets them as integer, but they are not. They shall be ordered like the list I give plotly.

By the way in matplotlib the order is right.

trace1 = go.Bar(
    x=consultants, 
    y=info[0,:]
)
trace2 = go.Bar(
    x=consultants,
    y=info[1,:],
)
trace3 = go.Bar(
    x=consultants,
    y=info[2,:]
)
trace4 = go.Bar(
   x=consultants,
   y=info[3,:]
)

data = [trace1, trace2, trace3, trace4]
layout = go.Layout(
       barmode='stack',
       xaxis=dict(
       categoryorder='array',
       categoryarray=consultants,
       titlefont=dict(
         size=18,
         color='black'),
       showticklabels=True,
       tickfont=dict(
        size=16,
        color='black',
        ),
    tickangle=20
    ),
yaxis=dict(
    title='Number of customers',
       titlefont=dict(
        size=18,
        color='black'),
    showgrid=True,
    showline=False,
    showticklabels=True,
    tickfont=dict(
        size=16,
        color='black')
    ),

  )

fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='stacked-bar')

回答1:


Interestingly Plotly seems to ignore categoryorder for integers but disabling of sorting can be achieved by passing type='category in xaxis in layout.

type ( enumerated : "-" | "linear" | "log" | "date" | "category" )

default: "-"
Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question.

import plotly
import plotly.graph_objs as go
import numpy as np

plotly.offline.init_notebook_mode()

consultants = [1, 3, 2, 5, 4]
info = np.random.randint(100, size=(5,5))

data = []
for i in range(len(info)):
    data.append(go.Bar(x=consultants, 
                       y=info[i,:]))

layout = go.Layout(barmode='stack', 
                   xaxis=dict(type='category'),
                   yaxis=dict(title='Number of customers'))

fig = go.Figure(data=data, layout=layout)
plotly.offline.iplot(fig, filename='stacked-bar')


来源:https://stackoverflow.com/questions/47489554/plotly-deactivate-x-axis-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!