0%

Python | 可视化 // Visualization

记录一些常用的Python绘图代码,为工作提效

常用图表

堆叠柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns

import warnings
warnings.filterwarnings('ignore')

## Load Data
df = sns.load_dataset('diamonds')
df.head() ## 预览数据,见下图

df.cut.unique()
# ['Ideal', 'Premium', 'Good', 'Very Good', 'Fair']
# Categories (5, object): ['Ideal', 'Premium', 'Very Good', 'Good', 'Fair']

df.clarity.unique()
# ['SI2', 'SI1', 'VS1', 'VS2', 'VVS2', 'VVS1', 'I1', 'IF']
# Categories (8, object): ['IF', 'VVS1', 'VVS2', 'VS1', 'VS2', 'SI1', 'SI2', 'I1']

df.color.unique()
# ['E', 'I', 'J', 'H', 'F', 'G', 'D']
# Categories (7, object): ['D', 'E', 'F', 'G', 'H', 'I', 'J']

Data_diamonds_Preview

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sns.set_theme(style='ticks')
f, ax = plt.subplots(figsize=(7, 5))
sns.despine(f)

sns.histplot(
df,
x='price',
hue='cut',
multiple='stack', ## 堆叠
palette='light:m_r',
edgecolor='.3',
linewidth=.5,
log_scale=True,
)
ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
ax.set_xticks([500, 1000, 2000, 5000, 10000])

plt.savefig('histplot_stack.jpg', dpi=400)
plt.show()

堆积柱状图

词云图

双轴图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import matplotlib.pyplot as plt
import pandas as pd

## Data
df = pd.DataFrame([
[-2, 10, 0.8],
[-1, 20, 0.7],
[0, 30, 0.6],
[1, 40, 0.5],
[2, 50, 0.4],
[3, 60, 0.3]
], columns=['x', 'y1', 'y2'])

## Visualization
fig = plt.figure(figsize=(10, 6))

ax1 = fig.add_subplot(111)
ax1.bar(df.x, df.y1, color='g', label='y1')

ax2 = ax1.twinx()
ax2.plot(df.x, df.y2, color='r', label='y2')

## Legend
fig.legend(loc=1, bbox_to_anchor=(0.1, 1), bbox_transform=ax1.transAxes)

ax1.set_xlabel(r"X axis")
ax1.set_ylabel(r"Y1")
ax2.set_ylabel(r"Y2")

plt.savefig('Twin_Xaxes.jpg', dpi=400)
plt.show()

双轴图

参考资料

Thank you for your approval.

欢迎关注我的其它发布渠道