我有这个数据样本:
test = pd.DataFrame({'cluster':['1','1','1','1','2','2','2','2','2','3','3','3'],
'type':['a','b','c','a','a','b','c','c','a','b','c','a']})我使用交叉表生成一个新的数据和绘图结果:
pd.crosstab(test.cluster,test.type,normalize='index',margins=True).plot(kind='bar')

我想画的行都是点缀的水平基准线,颜色相同,对应于每一种类型,以提高对情节的理解。会感谢这个社区的帮助!
发布于 2018-11-25 12:19:10
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(
{'cluster': ['1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '3', '3'],
'type': ['a', 'b', 'c', 'a', 'a', 'b', 'c', 'c', 'a', 'b', 'c', 'a']})
tab = pd.crosstab(test.cluster, test.type, normalize='index', margins=True)
fig, ax = plt.subplots()
# find the default colors
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
# make a bar plot using all rows but the last
tab.iloc[:-1].plot(ax=ax, kind='bar', color=colors)
# draw the horizontal dotted lines
for y, c in zip(tab.loc['All'], colors):
ax.axhline(y=y, color=c, linestyle=':', alpha=0.5)
plt.show()

https://stackoverflow.com/questions/53467225
复制相似问题