【发布时间】:2020-10-22 01:36:37
【问题描述】:
我想制作一个 n 元素的部分堆叠条形图,其中 n - 1 个元素堆叠,其余元素是与堆叠条形相邻的另一个条形图等宽。相邻的条形元素绘制在辅助 y 轴上,通常是百分比,绘制在 0 和 1 之间。
我目前使用的解决方案能够很好地表示数据,但我很想知道如何在堆叠条旁边实现等宽单条的预期结果。
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
mylabels=list('BCD')
df = pd.DataFrame(np.random.randint(1,11,size=(5,4)), columns=list('ABCD'))
df['A'] = list('abcde')
df['D'] = np.random.rand(5,1)
ax = df.loc[:,~df.columns.isin(['D'])].plot(kind='bar', stacked=True, x='A', figsize=(15,7))
ax2 = ax.twinx()
ax2.bar(df.A,df.D, color='g', width=.1)
ax2.set_ylim(0,1)
handles, labels = ax.get_legend_handles_labels()
green_patch = mpatches.Patch(color='g')
handles.append(green_patch)
ax.legend(handles=handles, labels=mylabels)
ax.set_xlabel('')
【问题讨论】:
标签: python pandas matplotlib