如何处理Pandas酒吧的恼人差距

2024-10-05 11:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在下面的条形图中弥补2012年和2013年之间的差距。在

enter image description here

我的数据帧是

In [30]: df
Out[30]:
            Pre-Release  Post-Release
FinishDate
2008                1.0           0.0
2009               18.0           0.0
2010               96.0           0.0
2011              161.0           0.0
2012              157.0           0.0
2013                0.0         139.0
2014                0.0         155.0
2015                0.0         150.0
2016                0.0          91.0
2017                0.0          15.0

我用df.plot(kind='bar', width=1)来绘图。在


Tags: 数据in绘图dfreleaseplotbarout
3条回答

每年绘制两个数据集。因此,在x轴上的每个节点上,两个数据集都绘制了两个条形图。你看不到它们,因为值是零。我认为关键字stacked=True可能有用。这两个数据集都是垂直堆叠的,没有间隙显示。在

在你的图表中没有实际的“间隙”:熊猫只是预留空间来绘制相邻的两个不同的条形图。用这段代码来说明:

from io import StringIO
import pandas as pd
TESTDATA=StringIO("""2008                1.0           0.0
2009               18.0           5.0
2010               96.0           0.0
2011              161.0           0.0
2012              157.0           0.0
2013                0.0         139.0
2014                0.0         155.0
2015                0.0         150.0
2016                0.0          91.0
2017                0.0          15.0""")
df=pd.read_csv(TESTDATA,delim_whitespace=True,index_col=0)
df.plot(kind='bar')

Two bars next to each other

但实际上不需要将两个条形图并排打印,因此,您可以将两个系列绘制到同一个图形中,而不是绘制数据帧:

^{pr2}$

enter image description here

或者只需使用:

df.plot(kind='bar', stacked=True)

在这个例子中会得到相同的结果。在

实际上,差距通常是您想要的行为,因为您正在有效地绘制两个柱状图。在

然而,在这种情况下,报告的值似乎是排他的,所以没有必要并排绘制直方图,而是只绘制一个然后另一个。在

下面是一个最简单的例子,可以帮助您达到目的:

import matplotlib.pyplot as plt
import numpy as np
import pandas

someDF = pandas.DataFrame({'1':np.random.uniform(size=20)*10, '2':np.random.uniform(size=20)*10})

cut = 10
fig, ax = plt.subplots(figsize=(8,3))

first = someDF['1'][someDF.index >= cut]
second = someDF['2'][someDF.index < cut]

ax.bar(left=first.index, height=first, align='center', color='blue')
ax.bar(left=second.index, height=second, align='center', color='red')
plt.show()

输出看起来像: enter image description here

相关问题 更多 >

    热门问题