Pandas数据框图条下降值

问题描述 投票:2回答:1

在进行数据分析时,我使用pandas Dataframe的df.plot.bar方法来绘制我的结果:

df.plot.bar(figsize=(15, 5), legend=None)

在进行更多研究时,我注意到,在某些情况下,情节看起来有所不同。原因是,当figsize太低时,plot.bar方法开始忽略信息。

我的例子每个事件有31个条形,而在figsize=(10, 5)的条形图比figsize(15, 5)更少。这是已知和期望的行为吗?因为没有警告,情节错过了(重要的)信息。

数据帧:

                 Day(X-Axis in plot)
+------------+-----------------------+
| Id    +  Day1  |   Day2  |   Day3  ...
+------------+-----------------------+
| 0     + 0      |   20    |    0
| 1     | 300    |   10    |    400
| 3     + 20     |   0     |    400
| 4     | 60     |   0     |    800
...
+------------+-----------------------+

值是特定日期特定ID的总体。

每个id每天都有自己的栏。数据帧用T转置,以使plot.bar绘制X轴上的天数。

figsize=(10, 5)

figsize(10, 5)

figsize(15, 5)

figsize(15, 5)

python pandas dataframe matplotlib plot
1个回答
2
投票

估计:你有12行31列。酒吧占据了单位空间的80%。条形图应至少宽两个像素才能在屏幕上看到。通常的数字在轴的两侧都有10%的余量,并且有100 dpi。然后你需要一个2 * 12 * 31 / 0.8 ** 2 / 100~ = 12英寸的图形宽度。换句话说,如果您有超过31列,则在12英寸宽的数字上可能看不到某些条形。

为了使这个可重复,让我们考虑以下情况,我们有N=20行和列。

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

N=20
df = pd.DataFrame(np.diag(np.ones(N)))

ax = df.plot.bar(legend=False)

plt.show()

enter image description here

这里有些酒吧不可见。我们可以计算出20行和20列的数字需要为2*N**2/0.8**2/100. == 12.5英寸宽度。

N=20
df = pd.DataFrame(np.diag(np.ones(N)))

w = 2*N**2/0.8**2/100.
plt.rcParams.update({"figure.figsize" : (w, 4.8), "figure.dpi" : 100})
ax = df.plot.bar(legend=False)

现在它确实显示了所有的酒吧。

enter image description here

当然,图形不能任意大,因此可以确保条形具有边缘线,该边缘线将被绘制而与矩形的范围无关。

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

N=20
df = pd.DataFrame(np.diag(np.ones(N)))

ax = df.plot.bar(legend=False)
for bar in ax.patches:
    bar.set_linewidth(0.72)
    bar.set_edgecolor(bar.get_facecolor())
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.