如何绘制多个列

2024-09-29 19:32:21 发布

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

我有数据帧total_year,它包含三列(yearactioncomedy

total_year

enter image description here

我想在x轴上绘制year列,以及action&comedy都在y轴上

如何在y轴上绘制两列(actioncomedy

我的代码只在y轴上绘制一列

total_year[-15:].plot(x='year', y='action', figsize=(10,5), grid=True)

enter image description here


Tags: 数据代码trueplot绘制actionyeargrid
3条回答

可以为函数的y参数提供多个列名。这些应该在list中指定,如下所示

df.plot(x="year", y=["action", "comedy"])

完整示例:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"year": [1914,1915,1916,1919,1920],
                   "action" : [2.6,3.4,3.25,2.8,1.75],
                   "comedy" : [2.5,2.9,3.0,3.3,3.4] })
df.plot(x="year", y=["action", "comedy"])
plt.show()

enter image description here

Pandas.DataFrame.plot()默认情况下,使用索引绘制X轴,所有其他数值列将用作Y

因此,将year列设置为索引将实现以下功能:

total_year.set_index('year').plot(figsize=(10,5), grid=True)
  • 当使用^{}时,只需要为x参数指定一列。
    • 需要注意的是,具有numeric值的其余列将用于y
    • 下面的代码包含要演示的额外列。注意,'date'保留为string。但是,如果将'date'转换为datetime{},则绘图API还将在y轴上绘制'date'
  • 如果dataframe包含许多列,其中一些列不应打印,则指定y参数,如此answer中所示,但如果dataframe仅包含要打印的列,则仅指定x参数
  • 如果索引用作x轴,则无需指定x=
import pandas as pd

# test data
data = {'year': [1914, 1915, 1916, 1919, 1920],
        'action': [2.67, 3.43, 3.26, 2.82, 1.75],
        'comedy': [2.53, 2.93, 3.02, 3.37, 3.45],
        'test1': ['a', 'b', 'c', 'd', 'e'],
        'date': ['1914-01-01', '1915-01-01', '1916-01-01', '1919-01-01', '1920-01-01']}

# create the dataframe
df = pd.DataFrame(data)

# display(df)
   year  action  comedy test1        date
0  1914    2.67    2.53     a  1914-01-01
1  1915    3.43    2.93     b  1915-01-01
2  1916    3.26    3.02     c  1916-01-01
3  1919    2.82    3.37     d  1919-01-01
4  1920    1.75    3.45     e  1920-01-01

# plot the dataframe
df.plot(x='year', figsize=(10, 5), grid=True)

enter image description here

相关问题 更多 >

    热门问题