数据可视化
学习资料:https://github.com/datawhalechina/hands-on-data-analysis
一、图表代码编写
在 Python 中,matplotlib 是最常用的数据可视化库之一,结合 pandas 可以方便地对数据进行处理和可视化。以下是一些常用图表的代码编写示例:
折线图:
1 2 3 4
| import matplotlib.pyplot as plt data = [1, 2, 3, 4, 5] plt.plot(data) plt.show()
|
柱状图:
1 2 3 4 5
| import pandas as pd data = {'Category': ['A', 'B', 'C'], 'Value': [10, 15, 7]} df = pd.DataFrame(data) df.plot(kind='bar', x='Category', y='Value') plt.show()
|
饼图:
1 2 3 4 5 6
| sizes = [215, 130, 245, 210] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) plt.axis('equal') plt.show()
|
散点图:
1 2 3 4
| x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11] y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78] plt.scatter(x, y) plt.show()
|
直方图:
1 2 3
| data = np.random.randn(1000) plt.hist(data, bins=30) plt.show()
|
箱线图:
1 2 3
| data = [np.random.normal(0, std, 100) for std in range(1, 4)] plt.boxplot(data, vert=True, patch_artist=True) plt.show()
|
二、数据可视化常用技巧
设置图表标题和坐标轴标签
1 2 3
| plt.title('My Title') plt.xlabel('X Axis Label') plt.ylabel('Y Axis Label')
|
设置图表样式
1
| plt.style.use('seaborn-darkgrid')
|
添加图例
保存图表
1
| plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')
|
三、结合 Pandas 快速绘图
1 2 3 4 5
| df.plot(kind='bar', x='col1', y='col2') df.plot(kind='scatter', x='col1', y='col2') df.plot(kind='hist', bins=30) df.plot(kind='box') df.plot(kind='line')
|