【问题标题】:Matplotlib bar chart from two variable column - Pandas data manipulation (mostly)来自两个变量列的 Matplotlib 条形图 - Pandas 数据操作(主要是)
【发布时间】:2023-03-14 07:35:01
【问题描述】:

注意:下面发布解决方案!!!

我有一个时间索引表,其中的 BLIP 列只有两个值“XX”和“YY”。目标是显示“XX”和“YY”的计数,其中“YY”位于 x 轴下方。我正在尝试使用 Wes McKenney 的数据分析书(我认为是第 26 页)中的代码从 pandas 表中创建正确的数据结构:

df = base_df.drop(columns=dropcols).set_index('Created')
group = ['f2','BLIP']
df0 = df_minus.groupby(group)
agg_counts = df0.size().unstack().fillna(0)
indexer = agg_counts.sum(1).argsort()
count_subset = agg_counts.take(indexer).copy()
table = count_subset.groupby('BLIP').resample('MS').count().unstack('BLIP')['BLIP']
chart = table.plot.bar(title = chart_title, x=None, color = ['green', 'red', 'grey']);

线

agg_counts = df0.size().unstack().fillna(0) 

导致以下错误:

TypeError: 'numpy.int32' object is not callable

我在这里找到了这个 sn-p 的瑰宝,但找不到解密它的文档。

data['values'].plot(kind='bar', color=data.positive.map({True: 'g', False: 'r'}))

这似乎很简单,但我对这个轴很感兴趣。

pandas 表格格式类似于

create_date f1 f2 f3 BLIP f5...
dt_stamp    X  Y  Z  XX   K1
dt_stamp    S  R  Y  YY   K3
dt_stamp    P  P  T  XX   K1

等等。

按照 Jesse 的建议,我尝试了

df_plus =df[df['BLIP']=='XX']
df_minus=df[df['BLIP']=='YY']

ax = plt.axes()
ax.bar(df_plus.index, df_plus['BLIP'], width=0.4, color='g')
ax.bar(df_neg.index, df_minus['BLIP'], width=0.4, color='r')
ax.autoscale()
plt.show()

这导致了

ValueError: shape mismatch: objects cannot be broadcast to a single shape

整体解决方案

df = base_df
plt.clf()
fig = plt.figure()
width = 8
height = 6
fig.set_size_inches(width, height)
chart_title = 'YTD CR Trend Summary'
df_plus =df[df['BLIP'] == 'XX']
df_minus=df[df['BLIP']== 'IYY']
p =  df_plus.resample('MS').count()['BLIP'].fillna(0)
n = df_minus.resample('MS').count()['BLIP'].apply(lambda x: int(-x)) 
print(chart_title, len(df), p.sum(), n.sum())
plt.clf()
fig = plt.figure()
# ax = fig.add_subplot(1, 1, 1)
ax = plt.axes(label=chart_title) #label suppresses warning
if p.sum() != False:
    ax.bar(p.index, p, width=10, color='g') 
if n.sum() != False:
    ax.bar(n.index, n, width=10, color='r')
plt.suptitle(chart_title, fontsize=11)
filename = f'{graph_images_dir}{chart_title}.png'
print(f'Saving {filename}')
plt.savefig(filename,  bbox_inches='tight', pad_inches=0.5, dpi=200)
plt.show()

【问题讨论】:

  • 我想知道是否可以使用 data.positive.map 直接映射到 BLIP 中的“XX”值,或者我是否必须创建一个具有 True 和 False 值的新字段。
  • 似乎我必须从这个 3NF 数据框转到某种对象,按月给我一个带有 BLIP.value_counts 的对象,然后我需要以某种方式将它们正确映射到绘图,

标签: python pandas matplotlib


【解决方案1】:

您可以使用 matplotlib 手动绘制它:

import matplotlib.pyplot as plt

ax = plt.axes()
ax.bar(table.index, table['XX'], width=0.4, color='g')
ax.bar(table.index, table['YY'], width=0.4, color='r')

【讨论】:

  • 我把表格分成两个数据框df_pos和df_neg,然后尝试ax.bar(table.index, df_pos['BLIP'], width=0.4, color='g') 得到这个错误ValueError:形状不匹配:无法将对象广播到单个形状
  • 这意味着您的table.index 的长度与df_pos['BLIP'] 的长度不同。你可以改用df_pos.index
  • 上面发布的解决方案。 Jesse 的建议是正确的,但是 table['XX'] 应该是 table['BLIP'] 警告:睡眠不足时不要编码!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2021-06-04
相关资源
最近更新 更多