從默認(rèn)的Python折線圖到雜志級(jí)別的高質(zhì)量 infographic圖表設(shè)計(jì)
图片,作者提供
使用过 Matplotlib 的人都知道默认的图表有多难看。在这系列文章中,我将分享一些技巧来让你的可视化效果更加突出,体现你的个人风格。
我们从一个简单的折线图开始,折线图是一种非常常见和常用的图表。重点是为图表下方添加一个渐变填充——这并不是一个很直接的任务。
那么就让我们开始吧,一步步来,走过这个转变的所有关键步骤!
我们先导入所需的模块。
import pandas as pd # 导入pandas库,用于数据处理
import numpy as np # 导入numpy库,用于数值计算
import matplotlib.dates as mdates # 导入matplotlib的dates模块,用于日期处理
import matplotlib.pyplot as plt # 导入matplotlib的pyplot模块,用于绘图
import matplotlib.ticker as ticker # 导入matplotlib的ticker模块,用于设置轴刻度
from matplotlib import rcParams # 从matplotlib导入rcParams,用于设置图形参数
from matplotlib.path import Path # 从matplotlib导入Path,用于定义路径
from matplotlib.patches import PathPatch # 从matplotlib导入PathPatch,用于绘制路径补丁
np.random.seed(38) # 设置随机数种子为38,以保证结果的可重复性
现在我们需要为我们的可视化生成一些样本数据,比如类似股票价格走势的数据。
dates = pd.date_range(start='2024-02-01', periods=100, freq='D') # 生成日期范围
initial_rate = 75 # 初始利率
drift = 0.003
波动率 = 0.1 # 波动率
returns = np.random.normal(drift, 波动率, len(dates)) # 收益率
rates = initial_rate * np.cumprod(1 + returns) # 计算累积产品
x, y = dates, rates
让我们看看用默认的Matplotlib设置看起来怎么样。
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(dates, rates)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=30))
plt.show()
默认图像,作者的这张图片
其实也没那么吸引人,对吧?但我们会让它看起来更顺眼。
- 设置标题
- 设置图表的基本参数,如大小和字体
- 将Y轴刻度移到右边
- 更改主线条的颜色、样式和粗细
# 瑞典参数改为“通用参数”或“一般参数”以准确反映源代码中的“General parameters”
fig, ax = plt.subplots(figsize=(10, 6))
plt.title("每日访客", fontsize=18, color="black")
rcParams['font.family'] = 'DejaVu Sans'
rcParams['font.size'] = 14
# Y轴移到右边
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
# 绘制主要数据线
ax.plot(dates, rates, color='#268358', linewidth=2)
应用了通用参数,图片由作者创作
好吧,现在看起来干净多了。
我们现在想在背景中添加极简网格,去掉边框,让界面看起来更简洁,并去掉Y轴的刻度。
# 网格设置。
ax.grid(color="gray", linestyle=(0, (10, 10)), linewidth=0.5, alpha=0.6)
ax.tick_params(axis="x", colors="black")
ax.tick_params(axis="y", left=False, labelleft=False)
# 边框设置。
ax.spines["top"].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines["bottom"].set_color("black")
ax.spines['left'].set_color('white')
ax.spines['left'].set_linewidth(1)
# 隐藏Y轴的刻度。
ax.tick_params(axis='y', length=0)
网格已加入,这张图片由作者提供。
我们现在要在X轴的第一个刻度附近添加一个小的美学细节,并且我们会把刻度标签的字体颜色调得更淡一些。
# 在轴上第一个日期加上年份
def 自定义日期格式(t, pos, dates, x_interval):
日期 = dates[pos*x_interval]
if pos == 0:
return 日期.strftime('%d %b \'%y')
else:
return 日期.strftime('%d %b')
ax.xaxis.set_major_formatter(ticker.FuncFormatter((lambda x, pos: 自定义日期格式(x, pos, dates=dates, x_interval=x_interval))))
# 将日期格式化为所需的格式
# 将每个刻度标签的颜色设置为 #808079
[t.set_color('#808079') for t in ax.yaxis.get_ticklabels()]
[t.set_color('#808079') for t in ax.xaxis.get_ticklabels()]
第一次约会前几天拍的照片,约: Author
而且我们正接近最棘手的部分——如何在曲线下方制作渐变效果。但实际上,Matplotlib 并没有提供这种功能,我们可以通过创建一个渐变图像,并用图表将其裁剪来模拟效果。
# 绘制梯度图
numeric_x = np.array([i for i in range(len(x))])
# 将numeric_x的最大值添加到numeric_x_patch的末尾
numeric_x_patch = np.append(numeric_x, max(numeric_x))
# 在numeric_x_patch前面添加numeric_x_patch的第一个元素
numeric_x_patch = np.append(numeric_x_patch[0], numeric_x_patch)
# 将0添加到y_patch的末尾
y_patch = np.append(y, 0)
# 在y_patch前面添加0
y_patch = np.append(0, y_patch)
# 创建路径对象
path = Path(np.array([numeric_x_patch, y_patch]).transpose())
# 创建路径补丁对象
patch = PathPatch(path, facecolor='none')
# 将路径补丁添加到当前坐标轴
plt.gca().add_patch(patch)
# 使用指定的颜色映射和透明度显示numeric_x的梯度图
ax.imshow(numeric_x.reshape(len(numeric_x), 1), interpolation="bicubic",
cmap='绿色',
origin='下部',
alpha=0.3,
extent=[min(numeric_x), max(numeric_x), min(y_patch), max(y_patch) * 1.2], # 定义显示区域
aspect="auto", clip_path=patch, clip_on=True) # 设置裁剪路径
添加了梯度,图片由作者提供 (作者)
现在看起来既整洁又漂亮。我们只需要用任何编辑器(我更倾向于用Google Slides)添加一些细节,比如标题、圆角边和一些数字标识。
最终的可视化效果图,由作者制作
下面的完整代码是用于复现可视化效果的:
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章