【问题标题】:Plotting 2 columns as 2 lines and 1 column as x axis on Dataframes在 Dataframes 上将 2 列绘制为 2 行,将 1 列绘制为 x 轴
【发布时间】:2019-09-01 14:08:06
【问题描述】:

我是熊猫和所有这些数据框的新手。我很想知道如何将当前代码转换为 plt.figure 。我想将 2 列(旅游收据、访客)绘制为线,同时将另一列作为 x 轴(季度)。

似乎这段代码有效。但我想知道是否有更好的方法,例如 plt.plot 但允许我将 x 轴设置为 Quarters 并将其他 2 列设置为线?

df1= df.set_index('Quarters').plot(figsize=(10,5), grid=True)

数据框(来自我的 csv 文件):

| Quarters | Tourism Receipts | Visitors |
| 2019 Q1  | 10               | 1        |
| 2019 Q2  | 20               | 2        |
| 2019 Q3  | 30               | 3        | 
| 2019 Q4  | 40               | 4        |


我理解下面这个方法

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(20,10))

plt.plot(x,y)
plt.title
plt.xlabel
plt.ylabel

我想询问是否有办法将'df.set_index'方法转换为plt?

【问题讨论】:

  • 图表与我当前的代码如下所示:imgur.com/a/N9CXSV0(抱歉,我无法将其与我的问题一起上传)

标签: pandas matplotlib


【解决方案1】:

您实际上可以将两者结合起来,使用 .plot 方法可以节省大量 pd 的工作量,并同时使用 matplotlib 功能来自定义输出。

这是解决此问题的示例代码:

from matplotlib import pyplot as plt
import pandas as pd
fig, ax = plt.subplots(1, figsize=(10, 10))

df.set_index('Quarters')[['Tourism Receipts', 'Visitors']].plot(figsize=(10,5), grid=True, ax=ax)

ax.set_yticks(range(-10, 41, 5))
# ax.set_yticklabels( ('{}%'.format(x) for x in range(0, 101, 10)), fontsize=15)
ax.set_xticks(df.Quarters)
ax.set_xticklabels(["{} Q{}".format('2019', x) for x in df.Quarters])
ax.legend(loc='lower left')

您也可以对yticks 执行相同的操作。

PS:df.Quarters 不包括年份,所以我假设是 2019 年。

【讨论】:

  • 嗨@iDrwish - 谢谢你的帮助。我复制粘贴了代码,但遇到了一条很长的错误消息,我不确定我应该如何解决它......这是图片:imgur.com/a/yR7QMRU
  • 这是指df.Quarter中的格式错误,不能作为轴。您能否扩展您的数据样本以包含其中一些行?
  • @Grappyzxc 列Quarter 的数据类型是什么。
  • 它声明了对象
  • 以下返回什么:type(df.Quarters.iloc[0])? @Grappyzxc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2015-03-30
  • 1970-01-01
相关资源
最近更新 更多