先放原图
代码
from dateutil.parser import parse
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
df = pd.read_csv('owid-covid-data.csv', parse_dates=['date'])
# 要用到的国家列表
countries = ["United States", "India", "Brazil"]
# 要用到的颜色列表
colors = ["#666666", "#FF4136", "#188CE5"]
# 用于横坐标轴标签
date_list = [parse(date).strftime('%d %b') for date in pd.date_range('2020-1-1', periods=10, freq='M').astype(str)]
# 自定义图例句柄
class MyHandler:
def __init__(self, c):
self.color = c
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = FancyBboxPatch([x0, y0], 2, 8, # 左下角坐标、宽度、长度
fc=self.color, ec='white',
boxstyle="round,pad=8", # 指定类型为圆角
transform=handlebox.get_transform())
handlebox.add_artist(patch)
return patch
# 正式画图
fig, ax = plt.subplots(figsize=(15,5), dpi=200)
for i, country in enumerate(countries):
county = df[df['location'] == country]
ax.plot(county.date, county['new_cases_smoothed'], c=colors[i], lw=3, label=country)
# 隐藏上、右侧框线
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_color('#A8A8A8')
ax.spines['bottom'].set_color('#A8A8A8')
# 设置横纵坐标轴
ticks = ax.get_xticks()
plt.xticks(ticks=ticks, labels=date_list, rotation=45, color='#616161', fontsize=13)
plt.yticks(ticks=np.arange(0, 110000, 10000), color='#616161', fontsize=13)
plt.grid(axis='y', color='#A8A8A8')
# 设置图例
handles, labels = ax.get_legend_handles_labels()
plt.legend(ncol=3, bbox_to_anchor=(-0.07, 1.02), loc='lower left', fontsize=16, frameon=False,
handletextpad=-1.1, columnspacing=1.3,
#图例与文字间的距离 图例间的距离
handler_map={handles[0]: MyHandler('#666666'),
handles[1]: MyHandler('#FF4136'),
handles[2]: MyHandler('#188CE5')})
plt.show()
效果如下