Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly deactivate x axis sorting

Tags:

python

plotly

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')
like image 397
user47091 Avatar asked Nov 25 '17 19:11

user47091


2 Answers

The lastest version of Plotly now has a variable in the layout options to specify a categorical layout for the X axis:

fig.update_layout(
xaxis_type = 'category'
)
like image 130
Jaydeep Mistry Avatar answered Nov 12 '22 00:11

Jaydeep Mistry


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.

enter image description here

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')
like image 39
Maximilian Peters Avatar answered Nov 12 '22 02:11

Maximilian Peters