【问题标题】:Formatting plots with Matplotlib使用 Matplotlib 格式化绘图
【发布时间】:2020-01-04 01:20:03
【问题描述】:

我是 Pandas 和 Matplotlib 的初学者,我对使用 pandas 时的绘图格式有一些疑问。我有以下区域图代码:

import pandas as pd
from matplotlib import pyplot as plt

ax= wind_data.plot.area()
plt.legend(loc='center left', bbox_to_anchor= (1.0, 0.5))
plt.grid(False)
ax.set_facecolor("white")
ax.set_xlabel("Time of day")
ax.set_ylabel("Power in kW")
ax.set_xlim(0,24)
ax.set_ylim(0,50)

现在我想改变以下几个方面:

  • x 轴上的值是一天中的时间。它们应该从 00:00 - 24:00 开始显示。所以每个小时都应该有一个条目。由于空间不足,条目应垂直(而不是水平)书写
  • 当我导出 png 文件时,绘图周围有一个灰色框。这不应该是这样。相反,应该有一条细黑线作为轮辋
  • 我想在 y 轴的每个入口处都有一些水平线。这条线不应该太强,而应该以某种方式透明,以便您可以看到它,而不会占主导地位。

是否可以使用 Matplotlib(或任何其他 python 库)来做到这一点?

编辑:这里有输入数据:

Building 1  Building 2  Building 3  Building 4  Building 5
7.04    7.04    7.04    7.04    7.04
6.36    6.36    6.36    6.36    6.36
6.4     6.4     6.4     6.4     6.4
6.1     6.1     6.1     6.1     6.1
5.88    5.88    5.88    5.88    5.88
6.18    6.18    6.18    6.18    6.18
6.16    6.16    6.16    6.16    6.16
5.82    5.82    5.82    5.82    5.82
5.28    5.28    5.28    5.28    5.28
4.82    4.82    4.82    4.82    4.82
4.18    4.18    4.18    4.18    4.18
4.02    4.02    4.02    4.02    4.02
4.08    4.08    4.08    4.08    4.08
4.24    4.24    4.24    4.24    4.24
6.24    6.24    6.24    6.24    6.24
8.44    8.44    8.44    8.44    8.44
8.72    8.72    8.72    8.72    8.72
8.06    8.06    8.06    8.06    8.06
7.16    7.16    7.16    7.16    7.16
6.52    6.52    6.52    6.52    6.52
7.16    7.16    7.16    7.16    7.16
7.88    7.88    7.88    7.88    7.88
8.44    8.44    8.44    8.44    8.44
8.56    8.56    8.56    8.56    8.56

编辑:在 Jupyter 中使用 JohanC 的解决方案代码时出现错误消息

AttributeError                            Traceback (most recent call last)
<ipython-input-5-51251d64e3e0> in <module>()
     21 ax.set_xlim(1, 24)
     22 ax.set_ylim(0, 50)
---> 23 plt.xticks(wind_data.index, labels=[f'{h:02d}:00' for h in wind_data.index], rotation=90)
     24 plt.grid(axis='y', alpha=.4)
     25 plt.tight_layout()

C:\Users\wi9632\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\pyplot.py in xticks(*args, **kwargs)
   1704     if len(kwargs):
   1705         for l in labels:
-> 1706             l.update(kwargs)
   1707 
   1708     return locs, silent_list('Text xticklabel', labels)

C:\Users\wi9632\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\text.py in update(self, kwargs)
    241         """
    242         bbox = kwargs.pop('bbox', None)
--> 243         super(Text, self).update(kwargs)
    244         if bbox:
    245             self.set_bbox(bbox)  # depends on font properties

C:\Users\wi9632\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
    883         try:
    884             ret = [_update_property(self, k, v)
--> 885                    for k, v in props.items()]
    886         finally:
    887             self.eventson = store

C:\Users\wi9632\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in <listcomp>(.0)
    883         try:
    884             ret = [_update_property(self, k, v)
--> 885                    for k, v in props.items()]
    886         finally:
    887             self.eventson = store

C:\Users\wi9632\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\artist.py in _update_property(self, k, v)
    876                 func = getattr(self, 'set_' + k, None)
    877                 if func is None or not six.callable(func):
--> 878                     raise AttributeError('Unknown property %s' % k)
    879                 return func(v)
    880 

AttributeError: Unknown property labels

【问题讨论】:

  • 这些格式问题实际上是关于 matplotlib(Pandas 用于绘图的包)而不是 Pandas。搜索这些添加了“matplotlib”的东西应该会让你更接近答案。
  • 你能分享一些数据吗?很难知道你在策划什么
  • @CodeDifferent:我刚刚做到了

标签: python pandas matplotlib


【解决方案1】:

这是一个使用 matplotlib 的示例。现在使用来自更新问题的数据。

对于 xticks,刻度位置和标签可以使用 plt.xticks()`` 设置,它也接受旋转角度。要获得黑色边框,似乎需要通过plt.figure 设置linewidth,而edgecolor 是plt.savefig 的参数。

plt.grid 具有在一个或两个方向上显示网格线的参数。可以设置 alpha 值以使这些线条不那么突出或突出。

import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline

columns = ['Building 1', 'Building 2', 'Building 3', 'Building 4', 'Building 5']
power_values = [[7.04, 7.04, 7.04, 7.04, 7.04], [6.36, 6.36, 6.36, 6.36, 6.36], [6.4, 6.4, 6.4, 6.4, 6.4],
                [6.1, 6.1, 6.1, 6.1, 6.1], [5.88, 5.88, 5.88, 5.88, 5.88], [6.18, 6.18, 6.18, 6.18, 6.18],
                [6.16, 6.16, 6.16, 6.16, 6.16], [5.82, 5.82, 5.82, 5.82, 5.82], [5.28, 5.28, 5.28, 5.28, 5.28],
                [4.82, 4.82, 4.82, 4.82, 4.82], [4.18, 4.18, 4.18, 4.18, 4.18], [4.02, 4.02, 4.02, 4.02, 4.02],
                [4.08, 4.08, 4.08, 4.08, 4.08], [4.24, 4.24, 4.24, 4.24, 4.24], [6.24, 6.24, 6.24, 6.24, 6.24],
                [8.44, 8.44, 8.44, 8.44, 8.44], [8.72, 8.72, 8.72, 8.72, 8.72], [8.06, 8.06, 8.06, 8.06, 8.06],
                [7.16, 7.16, 7.16, 7.16, 7.16], [6.52, 6.52, 6.52, 6.52, 6.52], [7.16, 7.16, 7.16, 7.16, 7.16],
                [7.88, 7.88, 7.88, 7.88, 7.88], [8.44, 8.44, 8.44, 8.44, 8.44], [8.56, 8.56, 8.56, 8.56, 8.56]]
wind_data = pd.DataFrame(power_values, index=range(1, 25), columns=columns)
fig = plt.figure(linewidth=1, figsize=(7, 5))
ax = wind_data.plot.area(ax=plt.gca(), color=plt.get_cmap('Set1').colors)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
ax.set_facecolor("white")
ax.set_xlabel("Time of day")
ax.set_ylabel("Power in kW")
ax.set_xlim(1, 24)
ax.set_ylim(0, 50)
plt.xticks(wind_data.index, labels=[f'{h:02d}:00' for h in wind_data.index], rotation=90)
plt.grid(axis='y', alpha=.4)
plt.tight_layout()
plt.savefig('wind_data.png', edgecolor='black', dpi=300)
plt.show()

PS:如果您的 Python 版本早于 3.6,请将 f'{h:02d}:00' 替换为 '%02d:00' % h

【讨论】:

  • 感谢约翰的回答。不幸的是,当我将您发布的代码与 Jupyter 一起使用时,我遇到了很多错误。我编辑了原始帖子并添加了输入数据。也许这对你有帮助。
  • 对我来说它工作得很好,在笔记本里也一样。我用你的新数据更新了代码,所以我需要 24 而不是 25 个值。如果您仍然遇到问题,请在问题中添加错误消息。
  • 这似乎表明你有一个相当旧的 matplotlib 版本(早于 1.5,当前版本是 3.1.1)。可以试试升级吗?除此之外,我正在使用 f-strings,这是 Python 3.6 中的新功能,可以轻松地将数字集成到字符串中。
  • 如果您的文件以 csv 格式组织,您可以致电 wind_data = pd.read_csv("filename.csv") 。请参阅docsthis post。如果文件结构为标题行和值,则类似于read Excel files
  • "plt" 是库。 “fig”是一个变量,表示绘图中的一个分区。 “ax”是另一个变量,主要控制screen-x-y如何映射到x和y坐标。请参阅stackoverflow.com/questions/37970424/… 还有 plt.gca() 用于“获取当前轴”和 plt.gcf() 用于“获取当前图形”。通常 plt.something 会在内部转换为 plt.gca().something。因此,有很多重叠之处,并不总是很容易知道哪些功能在哪里。
猜你喜欢
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 2019-05-03
  • 2014-06-06
  • 2020-09-26
相关资源
最近更新 更多