如何绘制多个熊猫列
- 2025-02-11 09:51:00
- admin 原创
- 53
问题描述:
我有数据框,其中包含三total_year
列(year
,,)。action
`comedy`
如何在 y 轴上绘制两列(action
和)?我的代码只绘制一列:comedy
total_year[-15:].plot(x='year', y='action', figsize=(10,5), grid=True)
解决方案 1:
y
可以为pandas 绘图函数的参数提供多个列名。这些应在 中指定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()
解决方案 2:
Pandas.DataFrame.plot()
默认使用索引来绘制X
轴,所有其他数字列将用作Y
值。
因此将year
列设置为索引就可以达到目的:
total_year.set_index('year').plot(figsize=(10,5), grid=True)
解决方案 3:
使用时
pandas.DataFrame.plot
,只需要为x
参数指定一列。需要注意的是,其余具有
numeric
值的列将用于y
。以下代码包含额外的列以进行演示。注意,
'date'
保留为string
。但是,如果'date'
转换为datetime
dtype
,则 plot API 还将'date'
在 y 轴上绘制列。
如果数据框包含许多列,其中一些列不应绘制,则指定该参数,如该答案
y
所示,但如果数据框仅包含要绘制的列,则仅指定该参数。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)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD