如何在 DataFrame 中绘制多个数据列?
先决条件:熊猫
Python附带了许多有用的包,例如 pandas、matplotlib、numpy 等。要使用数据框,我们需要 Pandas 库,而要绘制数据框的列,我们需要 matplotlib。 Pandas与Matplotlib紧密集成。您可以使用plot()方法直接从 DataFrame 绘制数据。
要在单帧中绘制多个数据列,我们只需将列列表传递给 plot函数的 y 参数。下面给出了这样做的正确方法以及示例实现。
方法:
- 导入模块
- 创建或加载数据
- 转换为数据框
- 使用 plot() 方法,沿 X 轴指定单列,沿 Y 轴指定多列作为数组。
- 显示图。
下面是几个示例,它们说明了上述在 Dataframe 中绘制多个数据列的方法。
示例 1:
数据库:畅销书
Python3
import pandas as pd
import matplotlib.pyplot as mp
# take data
data = pd.read_csv("Bestsellers.csv")
# form dataframe
data = data.head()
df = pd.DataFrame(data, columns=["Name", "Price", "User Rating"])
# plot the dataframe
df.plot(x="Name", y=["Price", "User Rating"], kind="bar", figsize=(9, 8))
# print bar graph
mp.show()
Python3
import pandas as pd
import matplotlib.pyplot as mp
# data to be plotted
data = [["New York", 8.6, 20],
["Chicago", 2.7, 20],
["Los Angeles", 3.9, 20],
["Philadelphia", 1.5, 20],
["Houston", 2.1, 20]]
# form dataframe from data
df = pd.DataFrame(data, columns=["City", "Population(million)", "Year(2020)"])
# plot multiple columns such as population and year from dataframe
df.plot(x="City", y=["Population(million)", "Year(2020)"],
kind="line", figsize=(10, 10))
# display plot
mp.show()
输出:
示例 2:
蟒蛇3
import pandas as pd
import matplotlib.pyplot as mp
# data to be plotted
data = [["New York", 8.6, 20],
["Chicago", 2.7, 20],
["Los Angeles", 3.9, 20],
["Philadelphia", 1.5, 20],
["Houston", 2.1, 20]]
# form dataframe from data
df = pd.DataFrame(data, columns=["City", "Population(million)", "Year(2020)"])
# plot multiple columns such as population and year from dataframe
df.plot(x="City", y=["Population(million)", "Year(2020)"],
kind="line", figsize=(10, 10))
# display plot
mp.show()
输出: