我已经开始使用matplotlib / pandas。
我用熊猫创建了一个pivot_table,然后用matplotlib对其进行可视化。
这是截图:
奇怪的是,当将相同的数据(“ client_pivot”)构建到两个不同的图形(条形图和饼图)中时,它们相对于图例/键的行为有所不同。
尽管该栏在下面列出了标签。它似乎无法在图例中识别它们,也没有应用不同的配色方案。好像将它们视为大量数据一样...
您是否知道这是为什么以及我如何解决?
以下是相关代码的摘录(简而言之,不相关的代码已被删除)。
import pandas as pd
def reportMe(event):
csv_file = pd.read_csv("file.csv",
names = ['USER',
'CLIENT',
'TYPE',
'START',
'END',
'DURATION',
'NOTES'])
client_pivot = csv_file.pivot_table(index="CLIENT",
aggfunc="sum")
def pieMaker():
x_client = list(client_pivot.index)
y_duration = list(client_pivot["DURATION"])
fig = plt.figure(figsize=(12, 4))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.bar(x_client, y_duration) #bar
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(17)
ax1.tick_params(labelsize=7)
ax1.legend(x_client,
loc="center left",
bbox_to_anchor=(0.9, 0, 0.5, 1),
fontsize=7)
ax1.set_ylabel('Time (s)')
ax2.pie(y_duration, #pie
shadow=True,
autopct='%1.1f%%',
textprops={'fontsize': 7,
'color':'w'})
ax2.legend(x_client,
loc="center left",
bbox_to_anchor=(0.9, 0, 0.5, 1),
fontsize=7)
ax2.set_aspect(1)
plt.show()
pieMaker()
编辑:添加了饼图以进行比较
条形图被认为是单个实体,但如图所示,饼图楔形是单独的实体。这是一种风格选择;饼图没有标尺,该标尺用于描述各个面片,因此带有颜色的图例对于饼图很有用。条形图通常以相同的颜色显示,因此图例中只需要一个标签即可识别完整的条形图(并可能与其他条形图区分开)。
为了让每个栏分别出现在你可以提供给那些对传说handles
的说法legend
。
为了使条形变色,您可以使用默认颜色循环仪中的颜色并将其作为参数提供给color
。
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
a = .5+np.random.rand(5)
labs = list("ABCDE")
fig, (ax,ax2) = plt.subplots(ncols=2)
ax.pie(a)
ax.legend(labels=labs)
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
bars = ax2.bar(labs, a, color=colors)
ax2.legend(handles=bars, labels=labs)
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句