I want draw this char with plotly

my df is like this.
image

when i first draw like this,

weekend_data = seoul_moving[seoul_moving['์š”์ผ'].isin(['ํ† ', '์ผ'])]
grouped_weekend = weekend_data.groupby('์š”์ผ')['๋„์ฐฉ ์‹œ๊ตฐ๊ตฌ ์ฝ”๋“œ'].value_counts().unstack()
grouped_weekend.plot(kind='bar', stacked=True)
plt.title('์ฃผ๋ง ๋„์ฐฉ ์‹œ๊ตฐ๊ตฌ๋ณ„ ์œ ๋™์ธ๊ตฌ ๋น„์œจ')
plt.xlabel('์š”์ผ')
plt.ylabel('์œ ๋™์ธ๊ตฌ๋น„์œจ')
plt.legend(title='๋„์ฐฉ ์‹œ๊ตฐ๊ตฌ ์ฝ”๋“œ')
plt.show()

result is
image
(look color orderโ€ฆ order is same with arrival code)

bar is stacked by arrival_code.

but i want to bar is stacked by value order.

so i draw with this code

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

weekend_data = seoul_moving2[seoul_moving2['weekday'].isin(['saturday', 'sunday'])]
grouped_weekend = weekend_data.groupby('weekday')['arrival_code'].value_counts().unstack()
a=grouped_weekend
fig, ax = plt.subplots()
x = a.index
indexes = np.argsort(a.values).T
heights = np.sort(a.values).T
order = -1
bottoms = heights[::order].cumsum(axis=0)
bottoms = np.insert(bottoms, 0, np.zeros(len(bottoms[0])), axis=0)

colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
          '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
          '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5',
          '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5',
          '#393b79', '#637939', '#8c6d31', '#843c39', '#7b4173',
          '#5254a3', '#637939', '#8c6d31', '#843c39', '#7b4173']

# ์ƒ‰์ƒ ์ˆœํ™˜ ์„ค์ •
plt.rcParams['axes.prop_cycle'] = plt.cycler(color=colors)

mpp_colors = dict(zip(a.columns, plt.rcParams['axes.prop_cycle'].by_key()['color']))

for btms, (idxs, vals) in enumerate(list(zip(indexes, heights))[::order]):
    mps = np.take(np.array(a.columns), idxs)
    ax.bar(x, height=vals, bottom=bottoms[btms], color=[mpp_colors[m] for m in mps])
#ax.set_ylim(bottom=0, top=2)
plt.legend((np.take(np.array(a.columns), np.argsort(a.values)[0]))[::order], loc='upper right')

then result is this
image

i success draw with plt.

but i want draw with this plotly.

maybe,
i can draw with plotly with similar way.
for iteration + several barchart.

is there any simple way draw with plotly???

I am not sure if you could do it with a bar chart, I never used them so often.

But I think you could do it with a heatmap.

You would have the the weekday on the axis as you do. Each code gets an index based on the order of codes. This index is the position on the y axis.
The result would be something similar like this
heatmap

In my case there were company codes on the y-axis, but that is easy changable.

The process would be something like this:

  1. table = pd.pivot_table(
    weekend_data,
    index=[โ€œโ€˜์š”์ผโ€™โ€],
    columns=[โ€œ๋„์ฐฉ ์‹œ๊ตฐ๊ตฌ ์ฝ”๋“œโ€],
    values=[โ€œxyzโ€],
    aggfunc=โ€œcountโ€,
    )
    table = table.reset_index()
  2. You need several lists: list of weekdays, list of indices (position on the y axis), value_list (list of lists)
  3. add a heatmap trace
        self.fig.add_trace(
            go.Heatmap(
                z=value_list,
                x= list of weekdays,
                y= list of indices,
                xgap=1,
                ygap=1,
                showscale=False,
                colorscale=self.custom_color_scale, #Your color scale which would be a one to one matching 
                hoverongaps=False,
            )
        )

That would be the way I try it.

Using heatmap??OK i will try thanks!

Sure. Let me know how it goes and if you need some more help.

arrival_code is categorical data. not continuous.
11230, 11220 is a code of the place name (like Newyork, London)
so,
heatmap is not appropriate options.

but heatmap is good for continuous data,
because if i use continuout data, not categorical, just make two array can draw what i want easily

Iโ€™m not sure how you want it to look,but if youโ€™re aiming for something like what simon-u showed with a categorical Y-axis, would Gantt charts work?

In my case, I also used categories, which were company codes, weekdays or weeks and the values are number of documents released.

But I think the issue might be the colour scale. Your colour scale needs to support the number of codes you have, which might be a lot. Also you need to make sure its colouring by code.

I can have a look if you have a minimal example with some small dataset.

I SUCCESS!!!

you can test with this sample csv


import plotly.graph_objects as go
import plotly.colors as pc
import plotly.express as px
import pandas as pd

path = 'your file path'

sms = pd.read_csv(path,sep=",", encoding = 'UTF-8', index_col = 'Unnamed: 0')


data = []


weekend_data = sms[sms['weekday'].isin(['saturday', 'sunday'])]
grouped_weekend = weekend_data.groupby('weekday')['arrival_code'].value_counts().unstack()
df = grouped_weekend



color_map = px.colors.qualitative.Light24
color_map += color_map
mpp_colors = dict(zip(df.columns, color_map))


for i in range(df.shape[0]):
    ordered_columns = df.columns[1:][np.argsort(df.iloc[i, 1:].values)]
    ordered_columns = ordered_columns[::-1]
    for column in ordered_columns:

        data.append(go.Bar(x=[df.index[i]],
                           y=[df[column][i]],
                           marker=dict(color=mpp_colors[int(column)]),
                           name=column,
                           legendgroup=column,showlegend=i == 0))
                           
layout = dict(barmode='stack',
              yaxis={'title': 'amount'},
              xaxis={'type': 'category', 'title': 'month'})
fig = go.Figure(data=data, layout=layout)

fig.update_layout(
    title={
        'text': '<b>์ฃผ๋ง ๋„์ฐฉ ์‹œ๊ตฐ๊ตฌ๋ณ„ ์œ ๋™์ธ๊ตฌ ๋น„์œจ</b>',  
        'x': 0.5, 
        'y': 0.9,  
        'xanchor': 'center', 
        'yanchor': 'top',  
        'font': dict(
            family="Arial, sans-serif", 
            color="black", 
            size=20
        )
    },
        width=500,
    height=500,

)
fig.show()
1 Like