第4节,matplotlib设置线条的颜色和粗细

plot函数在作图时,color 参数可以控制线条的颜色,linewidth参数可以控制线条的粗细

import matplotlib
from matplotlib import pyplot as plt

matplotlib.rcParams['font.family'] = 'SimHei'

data = [{'年份': 2016, '收入': 14.5},
        {'年份': 2017, '收入': 15.6},
        {'年份': 2018, '收入': 17.9},
        {'年份': 2019, '收入': 23.4},
        {'年份': 2020, '收入': 18.6}
        ]

year = [str(item['年份']) for item in data]
income = [item['收入'] for item in data]

plt.plot(year, income, color='blue', linewidth=2.5,  marker='o', linestyle='solid')
plt.title('收入情况')
plt.xlabel('年份')
plt.ylabel('万元')
plt.show()

线条的颜色,我选择了蓝色,线条粗细我选择了2.5,效果如图
matplotlib 线条粗细

color可以接受非常多形式的颜色,上面实例给出的是最简单的,官方文档上给了一个实例,这里面的颜色,你可以任意选择

import matplotlib._color_data as mcd
import matplotlib.patches as mpatch
from matplotlib import pyplot as plt

overlap = {name for name in mcd.CSS4_COLORS
           if "xkcd:" + name in mcd.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcd.CSS4_COLORS[color_name]
    xkcd = mcd.XKCD_COLORS["xkcd:" + color_name].upper()

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(va='center', fontsize=10,
                     weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0 + col_shift, y_pos + .5, '  ' + css4, alpha=0.5, **text_args)
    ax.text(1 + col_shift, y_pos + .5, '  ' + xkcd, alpha=0.5, **text_args)
    ax.text(2 + col_shift, y_pos + .5, '  ' + color_name, **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.5, 'X11', ha='center', va='center')
    ax.text(1.5 + 3*g, -0.5, 'xkcd', ha='center', va='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()

效果图

扫描关注, 与我技术互动

QQ交流群: 211426309

加入知识星球, 每天收获更多精彩内容

分享日常研究的python技术和遇到的问题及解决方案