使用Matplotlib在数据子集上绘图

3
我会使用matplotlib来绘制数据框中的条形图。我使用以下结构首先绘制整个数据集:
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt 

Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ] )

现在我想绘制数据的同一列,但我想在特定的数据子集上这样做。对于'region_name'中的每个区域,我想生成条形图。这是我的DataFrame的一个示例。

enter image description here

我的尝试解决方案是写:

if weatherDFConcat['REGION_NAME'].any() == 'South':
    Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS'])
    df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
    df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ] )
    plt.show()

当我运行这段代码时,奇怪的是它只适用于“南部”地区。对于“南部”,图表会生成,但对于我尝试的任何其他地区,代码都会运行(我没有收到错误消息),但是图表从未显示出来。在除南部以外的任何地区运行我的代码都会在控制台中产生这种结果。

enter image description here

南部地区是我的DataFrame中的第一部分,该DataFrame有4000万行,其他地区在下面。我尝试绘制的DataFrame的大小是否会影响这个问题?


你尝试过使用该比较表达式将一个区域提取到另一个数据框中吗?这样行得通吗? - wwii
1个回答

2

如果我正确理解你的问题,你在绘图前想要做两件事:

  1. 根据 REGION_NAME 进行过滤。

  2. 在筛选后的数据框中,计算 TEMPBIN_CONS 列中每个值出现的次数。

你可以直接在 pandas 中完成这两件事情:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'STATE_NAME': ['Alabama', 'Florida', 'Maine', 'Delaware', 'New Jersey'],
                        'GEOID': [1, 2, 3, 4, 5],
                 'TEMPBIN_CONS': ['-3 to 0', '-3 to 0', '0 to 3', '-3 to 0', '0 to 3'],
                  'REGION_NAME': ['South', 'South', 'Northeast', 'Northeast', 'Northeast']},
                         columns=['STATE_NAME', 'GEOID', 'TEMPBIN_CONS', 'REGION_NAME'])

df_northeast = df[df['REGION_NAME'] == 'Northeast']
northeast_count = df_northeast.groupby('TEMPBIN_CONS').size()

print df
print df_northeast
print northeast_count

northeast_count.plot(kind='bar')
plt.show()

输出:

   STATE_NAME  GEOID TEMPBIN_CONS REGION_NAME
0     Alabama      1      -3 to 0       South
1     Florida      2      -3 to 0       South
2       Maine      3       0 to 3   Northeast
3    Delaware      4      -3 to 0   Northeast
4  New Jersey      5       0 to 3   Northeast

   STATE_NAME  GEOID TEMPBIN_CONS REGION_NAME
2       Maine      3       0 to 3   Northeast
3    Delaware      4      -3 to 0   Northeast
4  New Jersey      5       0 to 3   Northeast

TEMPBIN_CONS
-3 to 0    1
0 to 3     2
dtype: int64

enter image description here


非常感谢 - 简单的解决方案,完美地运作。我刚开始学习编程,非常感激。 - Justin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接