Matplotlib仿图--第一篇

先放原图
在这里插入图片描述
代码

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()

效果如下
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值