Beautification of chart style

1. Overview of chart styles

1.1 Default chart styles

1
2
3
import matplotlib

print(matplotlib.rc_params())

Params of chart styles

Common configuration items

Configuration items Instructions The default value
lines.color Line color ‘C0’
lines.linestyle Line type ‘-‘
lines.linewidth Line width 1.5
lines.marker Tag line ‘None’
lines.markeredgecolor Mark border color ‘auto’
lines.markeredgewidth Mark border width 1.0
lines.markerfacecolor Tag color auto
lines.markersize Markup size 6.0
font.family The system font [‘sans-serif’]
font.sans-serif Sans serif font [‘DejaVu Serif’, ‘Bitstream Vera Serif’, ‘Computer Modern Roman’, ‘New Century Schoolbook’, ‘Century Schoolbook L’, ‘Utopia’, ‘ITC Bookman’, ‘Bookman’, ‘Nimbus Roman No9 L’, ‘Times New Roman’, ‘Times’, ‘Palatino’, ‘Charter’, ‘serif’]
font.size The font size 10.0
font.style The font style ‘normal’
axes.unicode_minus Uses the Unicode encoded minus sign True
axes.prop_cycle Property circulator \cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’])
figure.constrained_layout.use Using constraint layouts False

1.2 Chart style modification

1
2
3
4
5
6
7
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], linewidth=3)

plt.rcParams['lines.linewidth'] = 3

plt.show()

or:

1
2
3
4
5
6
7
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], linewidth=3)

plt.rc('lines', linewidth=3)

plt.show()

Modify line width

2. Use color

2.1 Use basic color

Word abbreviation Word
c cyan
m megenta
y yellow
k black
r red
g green
b blue
w white

View all colors:

1
2
3
4
import matplotlib

for name, hex in matplotlib.colors.cnames.items():
print(name, hex)

View all colors

2.2 Using color mapping tables

1
2
3
import matplotlib.pyplot as plt

print(plt.colormaps())

Color maps

2.3 Demo1: Procurement of different types of books in the two regions

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 numpy as np

# Support Chinese
import matplotlib.pyplot as plt
import numpy as np

# Support Chinese
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

x = np.arange(5)
y1 = [1200, 2400, 1800, 2200, 1600]
y2 = [1050, 2100, 1300, 1600, 1340]
bar_width = 0.6
tick_label = ['家庭', '小说', '心理', '科技', '儿童']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x, y1, bar_width, color="#FFCC00", align="center", label="地区1")
ax.bar(x, y1, bar_width, bottom=y1, color="#B0C4DE", align="center",
label="地区2")
ax.set_xlabel("图书种类")
ax.set_ylabel("采购数量(本)")
ax.set_title("地区1和地区2对各类图书的采购情况")
ax.grid(True, axis="y", color="gray", alpha=0.2)
ax.set_xticks(x)
ax.set_xticklabels(tick_label)
ax.legend()

plt.show()

Procurement of different types of books in the two regions

3. Select line type

3.1 Select the type of line

Type of line

1
2
3
4
5
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], linestyle='--')

plt.show()

or

1
2
3
4
5
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], ls='--')

plt.show()

Long dotted line

3.2 Demo2: US dollar / RMB exchange rate trend in the international foreign exchange market in July 2017 and July 2019

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
32
33
import matplotlib.pyplot as plt
import numpy as np

# Chinese support
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# Data
eurcny_2017 = np.array([6.8007, 6.8007, 6.8015, 6.8015, 6.8060,
6.8060, 6.8060, 6.8036, 6.8025, 6.7877,
6.7835, 6.7758, 6.7700, 6.7463, 6.7519,
6.7511, 6.7511, 6.7539, 6.7265])
eurcny_2019 = np.array([6.8640, 6.8705, 6.8697, 6.8697, 6.8697,
6.8881, 6.8853, 6.8856, 6.8677, 6.8662,
6.8662, 6.8662, 6.8827, 6.8761, 6.8635,
6.8860, 6.8737, 6.8796, 6.8841])
date_x = np.array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 17, 18, 19, 24, 25, 26, 31])

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(date_x, eurcny_2017, color="#006374", linewidth=2,
label='2017年7月美元/人民币汇率')
ax.plot(date_x, eurcny_2019, color="#8a2e76", linestyle='--',
linewidth=2, label='2019年7月美元/人民币汇率')

ax.set_title('2017年7月与2019年7月美元/人民币汇率走势')
ax.set_xlabel('日期')
ax.set_ylabel('汇率')
ax.legend()

plt.show()

US dollar / RMB exchange rate trend in the international foreign exchange market in July 2017 and July 2019

4. Add data marker

4.1 Add data markers for line or scatter charts

matplotlib has many built-in data markers. Using these data markers, you can easily mark the data points for line chart or scatter chart. Data markers can be divided into filled data markers and unfilled data markers.

Filled data markers

Unfilled data markers

1
2
3
4
5
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], marker='*', markersize=20, markerfacecolor='y')

plt.show()

Add data markers

Learn more: matplotlib format string
Format string is a string that quickly sets the abbreviation of the basic style of lines.

[color][marker][linestyle]

1
2
3
4
5
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5], 'mo--')

plt.show()

Quickly sets style

4.2 Demo3: Mark quarterly sales of different products

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

sale_a = [2144, 4617, 7674, 6666]
sale_b = [853, 1214, 2414, 4409]
sale_c = [153, 155, 292, 680]

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(sale_a, 'D-', sale_b, '^:', sale_c, 's--')
ax.grid(alpha=0.3)
ax.set_ylabel('销售额(万元)')
ax.set_xticks(np.arange(len(sale_c)))
ax.set_xticklabels(['第1季度', '第2季度', '第3季度', '第4季度'])
ax.legend(['产品A', '产品B', '产品C'])

plt.show()

Mark quarterly sales of different products

5. Set font

5.1 Set font style

Common properties of the Text class
Common properties of the Text class

1
2
3
4
5
6
7
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 4, 5])
plt.text(1.9, 3.75, 'y=x+2', bbox=dict(facecolor='y'), family='serif',
fontsize=18, fontstyle='normal', rotation=-60)

plt.show()

Annotation text

5.2 Demo4: Maximum and minimum temperature in the next 15 days

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
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

x = np.arange(4, 19)
y_max = [32, 33, 34, 34, 33, 31, 30, 29, 30, 29, 26, 23, 21, 25, 31]
y_min = [19, 19, 20, 22, 22, 21, 22, 16, 18, 18, 17, 14, 15, 16, 16]

plt.plot(x, y_max, marker='o', label='最高温度')
plt.plot(x, y_min, marker='o', label='最低温度')

x_temp = 4
for y_h, y_l in zip(y_max, y_min):
plt.text(x_temp - 0.2, y_h + 0.7, y_h, family='SimHei',
fontsize=8, fontstyle='normal')
plt.text(x_temp - 0.2, y_l + 0.7, y_l, family='SimHei',
fontsize=8, fontstyle='normal')
x_temp += 1
plt.title('未来15天最高气温和最低气温的走势')
plt.xlabel('日期')
plt.ylabel(r'温度($^\circ$C)')
plt.ylim(0, 40)

plt.legend()
plt.show()

Maximum and minimum temperature in the next 15 days

6. Switch theme style

Show available style

1
2
3
import matplotlib.style as ms

print(ms.available)

Available style

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
import matplotlib.style as ms

ms.use('seaborn-dark')

plt.plot([1, 2, 3], [3, 4, 5], marker='*', markersize=20, markerfacecolor='y')

plt.show()

Use seaborn-dark style

7. Fill area

7.1 Fills the area between polygons or curves

  1. The fill() function is used to fill the polygon
1
2
3
4
ax.fill(x, y)                    # a polygon with default color
ax.fill(x, y, "b") # a blue polygon
ax.fill(x, y, x2, y2) # two polygons
ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon
  1. The fill_between() function is used to fills the area between two horizontal curves
1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 25, 500, endpoint=False)
cos_y = 0.5 * np.cos(0.5 * x)
sin_y = np.sin(x)

plt.fill_between(x, cos_y, sin_y, cos_y < sin_y, color='dodgerblue', alpha=0.5)
plt.fill_between(x, cos_y, sin_y, cos_y > sin_y, color='orangered', alpha=0.5)

plt.show()

Fill between

  1. The fill_betweenx() function is used to fills the area between two vertical curves
1
fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)

7.2 Demo5: Colored “snowflakes”

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
32
33
import matplotlib.pyplot as plt
import numpy as np


def koch_snowflake(order, scale=10):
def _koch_snowflake_complex(order):
if order == 0:
# Initial triangle
angles = np.array([0, 120, 240]) + 90
return scale / np.sqrt(3) * np.exp(np.deg2rad(angles) * 1j)
else:
ZR = 0.5 - 0.5j * np.sqrt(3) / 3
p1 = _koch_snowflake_complex(order - 1) # Start
p2 = np.roll(p1, shift=-1) # End
dp = p2 - p1 # Connect vector
new_points = np.empty(len(p1) * 4, dtype=np.complex128)
new_points[::4] = p1
new_points[1::4] = p1 + dp / 3
new_points[2::4] = p1 + dp * ZR
new_points[3::4] = p1 + dp / 3 * 2
return new_points

points = _koch_snowflake_complex(order)
x, y = points.real, points.imag
return x, y


x, y = koch_snowflake(order=5)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
ax.fill(x, y, facecolor='lightsalmon', edgecolor='orangered', linewidth=1)

plt.show()

Colored "snowflakes"


Beautification of chart style
https://www.hardyhu.cn/2022/03/17/Beautification-of-chart-style/
Author
John Doe
Posted on
March 17, 2022
Licensed under