在熊猫中绘图:使用子图时没有属性类型?

时间:2016-12-25 18:19:34

标签: python pandas matplotlib

我是绝对的pandas / matplotlib初学者,经过多次搜索,我无法弄清楚这个问题。

刚刚了解到为了格式化日期(基本上将它们分开),我需要另外处理一个名为fig的事情(图中):

fig, tg = plt.subplots(1)
tg.plot(pandoc['date_time'], pandoc['total_goals'], kind="bar")
tg.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
fig.autofmt_xdate()

但是,当我尝试将数据kind更改为“bar”时,我收到以下错误:

  

AttributeError:未知属性类型

当我完成时,它完美地运作了

pandoc['total_goals'].plot(kind='bar')

但是mdates.DateFormatter无效。

我错过了什么。它是什么?

1 个答案:

答案 0 :(得分:3)

Pandas DataFrames(例如pandoc)使用plot方法a kind parameter。 因此可以使用

制作情节
pandoc.plot(x='date_time', y='total_goals', kind="bar", ax=tg)

请注意,ax=tg用于告诉pandoc在matplotlib轴上绘制tg

相比之下,matplotlib轴(例如tg)具有plot方法,但tg.plot does not have a kind parameter。相反,要使用Axes对象创建条形图,请调用其tg.bar method

使用pandoc.plot方法,您可以使用类似

的方式制作条形图
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
np.random.seed(2016)

N = 150
pandoc = pd.DataFrame({'date_time':pd.date_range('2000-1-1', periods=N, freq='M'),
                   'total_goals':np.random.randint(10, size=N)})
fig, tg = plt.subplots(1)
pandoc.plot(x='date_time', y='total_goals', kind="bar", ax=tg)

labels, skip = ['']*N, 10
labels[skip//2::skip] = pandoc['date_time'].dt.strftime('%Y-%m-%d')[skip//2::skip]
tg.set_xticklabels(labels)

fig.autofmt_xdate()
plt.show()

enter image description here

请注意,tg.set_xticklabels用于设置xticklabels而不是mdates.DateFormatter。制作条形图时,基础条形图xtick的值为整数:

In [21]: tg.get_xticks()
Out[26]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

mdates.DateFormatter值为日期时,您只能使用xtick。 由于条形图具有固定数量的条形图,因此使用像mticker.FuncFormatter这样的动态格式化程序没有任何优势;您最好只使用xticklabels方法设置Axes.set_xticklabels

labels = ['']*N

创建N个空字符串列表。例如,['']*2评估为['', '']

x, y = a, b

equivalent to

x = a
y = b

所以labels, skip = ['']*N, 10等同于

labels = ['']*N
skip = 10

Python切片表示法,例如x[start:end:step]explained here。例如,

In [227]: x = list('ABCDEFGHIJK'); x
Out[227]: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

In [228]: x[1::3]
Out[228]: ['B', 'E', 'H', 'K']    <-- the first item is x[1], and then we pick up every 3rd item

因此,在上面的代码中,pandoc['date_time'].dt.strftime('%Y-%m-%d')是一系列字符串,如果我们称之为x,则x[skip//2::skip]是一个以x[skip//2]开头的新序列,然后步数skip金额。

skip//2使用integer-divisionskip除以2。

labelsN个空字符串列表开头。使用skip=10,分配

labels[skip//2::skip] = pandoc['date_time'].dt.strftime('%Y-%m-%d')[skip//2::skip]

使用skip//2中的日期字符串替换每个第10个元素(从pandoc['date_time'].dt.strftime('%Y-%m-%d')开始)。

pandoc['date_time']是一个时间序列。 pandoc['date_time'].dt.strftime('%Y-%m-%d')使用Series.dt.strftime method将日期格式化为%Y-%m-%d格式的日期字符串。