Pandas 提供了一种便捷的方式,可以直接使用 plot()
方法从 DataFrame 和 Series 中可视化数据。
此方法在后台使用 Matplotlib
库创建各种类型的图表。
让我们来学习 Pandas 中的可视化技术。
数据可视化数据集
我们将使用以下数据集来可视化数据。
汽车 | 重量 |
---|---|
Caterham | 0.48 吨 |
特斯拉 | 1.7 吨 |
奥迪 | 2 吨 |
宝马 | 2 吨 |
福特 | 2.5 吨 |
吉普 | 3 吨 |
数据可视化的折线图
在 Pandas 中,折线图将数据显示为由线连接的点序列。我们使用 plot()
函数绘制折线图,该函数接受两个参数:x
和 y
坐标。
让我们看一个例子。
import pandas as pd
import matplotlib.pyplot as plt
car = ["Caterham", "Tesla", "Audi", "BMW", "Ford", "Jeep"]
weight = [0.48, 1.7, 2, 2, 2.3, 3]
# create a DataFrame
data = {'Car': car, 'Weight': weight}
df = pd.DataFrame(data)
# plot using Pandas
df.plot(x='Car', y='Weight', kind='line', marker='o')
plt.xlabel('Car')
plt.ylabel('Weight')
plt.title('Car Weights')
plt.show()
输出

在这里,我们使用了 plot()
函数对给定数据集进行折线图绘制。我们将 plot()
的 x
和 y
坐标设置为 car 和 weight。
kind
参数设置为 'line'
以创建折线图,并将 marker 设置为 'o'
以在数据点显示圆形标记。
数据可视化的散点图
散点图将数据显示为点的集合。我们使用 kind = 'scatter'
的 plot()
函数绘制散点图。例如,
import pandas as pd
import matplotlib.pyplot as plt
car = ["Caterham", "Tesla", "Audi", "BMW", "Ford", "Jeep"]
weight = [0.48, 1.7, 2, 2, 2.3, 3]
# create a DataFrame
data = {'Car': car, 'Weight': weight}
df = pd.DataFrame(data)
# scatter plot using Pandas
df.plot(x='Car', y='Weight', kind='scatter', marker='o', color='blue')
plt.xlabel('Car')
plt.ylabel('Weight')
plt.title('Car Weights (Scatter Plot)')
plt.grid(True)
plt.show()
输出

在此示例中,我们在 plot()
方法中使用了 kind='scatter'
参数来创建散点图。
marker
参数设置为 'o'
以显示圆形标记,color
参数设置为 'blue'
以指定标记颜色。
数据可视化的条形图
条形图使用矩形框表示数据。在 Pandas 中,我们在 plot()
中传递 kind = 'scatter'
来绘制条形图。
让我们看一个例子。
import pandas as pd
import matplotlib.pyplot as plt
car = ["Caterham", "Tesla", "Audi", "BMW", "Ford", "Jeep"]
weight = [0.48, 1.7, 2, 2, 2.3, 3]
# create a DataFrame
data = {'Car': car, 'Weight': weight}
df = pd.DataFrame(data)
# bar graph using Pandas
df.plot(x='Car', y='Weight', kind='bar', color='green')
plt.xlabel('Car')
plt.ylabel('Weight')
plt.title('Car Weights (Bar Graph)')
plt.tight_layout()
plt.show()
输出

在这里,我们在 plot()
方法中使用了 kind='bar'
参数来创建条形图。color
参数设置为 'green'
以指定条形的颜色。
plt.tight_layout()
函数用于确保图表布局调整得当。
数据可视化的直方图
在 Pandas 中,我们在 plot()
中使用 kind='hist'
来创建直方图。例如,
import pandas as pd
import matplotlib.pyplot as plt
weight = [0.48, 1.7, 2, 3]
# create a DataFrame
data = {'Weight': weight}
df = pd.DataFrame(data)
# histogram using Pandas
df['Weight'].plot(kind='hist', bins=10, edgecolor='black', color='blue')
plt.show()
输出

在此示例中,我们使用 plot()
方法创建了权重的直方图,然后使用 plt.show()
显示它。
要了解更多信息,请访问 Pandas 直方图。