matplotlib科研绘图之折线图、柱状图、散点图、误差棒

 matplotlib折线图例子1

# -*- coding: utf-8 -*-
# @Time    : 2023/12/19 10:56
# @Author  : 长沙有肥鱼
# @FileName: 21.py
# @Software: PyCharm
# @Blog    : https://blog.csdn.net/weixin_53660567?spm=1010.2135.3001.5343

# 导入Matplotlib库
import matplotlib
import matplotlib.pyplot as plt

# 设置中文显示
matplotlib.rcParams['font.sans-serif'] = ['SimSun']  # 用宋体显示中文

# 数据
x = [25, 27.5, 31.5, 34]
y1 = [1.138, 1.242, 1.345, 1.428]
y2 = [1.260, 1.363, 1.465, 1.562]
y3 = [1.154, 1.271, 1.393, 1.464]
y4 = [1.170, 1.253, 1.373, 1.454]
y5 = [1.230, 1.313, 1.404, 1.504]

# 绘制折线图,每个数据集使用不同的标记、颜色和线型
plt.plot(x, y1, marker='*', ms=13, label="case 1", markerfacecolor='#FF0000',
         markeredgecolor='#FF0000', linestyle='-', linewidth=2.5, color='#FF0000')
plt.plot(x, y2, marker='D', ms=9, label="case 2", markerfacecolor='#FF9900',
         markeredgecolor='#FF9900', linestyle='-', linewidth=2.5, color='#FF9900')
plt.plot(x, y3, marker='d', ms=10, label="case 3", markerfacecolor='#0000FF',
         markeredgecolor='#0000FF', linestyle='-', linewidth=2.5, color='#0000FF')
plt.plot(x, y4, marker='v', ms=10, label="case 4", markerfacecolor='#00FF00',
         markeredgecolor='#00FF00', linestyle='--', linewidth=2.5, color='#00FF00')
plt.plot(x, y5, marker='o', ms=10, label="case 5", markerfacecolor='#FF00FF',
         markeredgecolor='#FF00FF', linestyle='-.', linewidth=2.5, color='#FF00FF')

# 设置x轴和y轴标签
plt.xticks(rotation=0, fontproperties='Times New Roman', fontsize=12)  # rotation=45
plt.yticks(rotation=0, fontproperties='Times New Roman', fontsize=12)
plt.xlabel("电压", fontsize=18)
plt.ylabel("电流", fontsize=18)

# 设置图表标题
plt.title("高压电站电压与电流的关系", fontsize=18)

# 更新图例字体大小和样式
plt.rcParams.update({'font.size': 15})
plt.legend(loc="upper left", prop='Times New Roman', fontsize=25, ncols=2, edgecolor='#C4C4C4',
           facecolor='white', fancybox=True, title_fontsize=25)

# 保存图表为图片文件
plt.savefig("21.png", dpi=1800)

# 显示图表
plt.show()

 matplotlib折线图例子2

import matplotlib.pyplot as plt
# import numpy as np

y1 = [2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
y2 = [3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
x = range(18, 31)

# 设置图形大小
plt.figure(figsize=(20, 7))

plt.plot(x, y1, label="自己本年度谈的对象数量", marker='D', markersize=10, markerfacecolor='cyan',
         markeredgecolor='cyan', color='cyan', linestyle='-', linewidth=3)
plt.plot(x, y2, label="同桌本年度谈的对象数量", marker='*', markersize=15, markerfacecolor='#FF0000',
         markeredgecolor='#FF0000', color='#FF0000', linestyle='--', linewidth=3)

# 设置x轴刻度
_xticks_labels = ["{}岁".format(i) for i in x]
plt.xticks(x, _xticks_labels, fontproperties='SimSun', fontsize=22)
plt.yticks(range(0, 9), fontproperties='Times New Roman', fontsize=22)

# 绘制网格
plt.grid(alpha=0.2)
plt.rcParams.update({'font.size': 20})  # 图例大小设置
plt.legend(prop='SimSun', fontsize=25, loc='best',  ncols=2, edgecolor='#C4C4C4',
           facecolor='white', fancybox=False, title_fontsize=25)  # 图例设置
plt.xlabel("年龄", fontsize=25, fontproperties='SimSun')  # x轴标签
plt.ylabel("对象数量", fontsize=25, fontproperties='SimSun')  # y轴标签

# 设置图表标题
plt.title("年龄与对象数量的关系", fontproperties='SimSun', fontsize=30)
# 显示图形
plt.savefig("D://matplotlib画图//学习//10.png", dpi=1200)
plt.show()

 marker设置

.:点(point marker)
,:像素点(pixel marker)
1:(tri_down marker)
2:(tri_up marker)
3:(tri_left marker)
4:(tri_right marker)
o:圆形(circle marker)
v:朝下三角形(triangle_down marker)
+:+号标记(plus marker)
x:x号标记(x marker)
D:菱形(diamond marker)
d:小型菱形(thin_diamond marker)
s:正方形(square marker)
p:五边星(pentagon marker)
*:星型(star marker)
h:1号六角形(hexagon1 marker)
H:2号六角形(hexagon2 marker)
|:垂直线形(vline marker)
_:水平线形(hline marker)
^:朝上三角形(triangle_up marker)
<:朝左三角形(triangle_left marker)
>:朝右三角形(triangle_right marker)

 color设置

matplotlib科研绘图之折线图、柱状图、散点图、误差棒_第1张图片

legend()设置

def __init__(
    self, parent, handles, labels,
    *,
    loc=None,
    numpoints=None,      # 图例线中的点数
    markerscale=None,    # 图例标记相对于原始标记的相对大小
    markerfirst=True,    # 图例标记和标签的左/右排序
    reverse=False,       # 图例标记和标签的反向排序
    scatterpoints=None,  # 散射点数量
    scatteryoffsets=None,
    prop=None,           # 图例文本的属性
    fontsize=None,       # 关键字直接设置字体大小
    labelcolor=None,     # 关键字来设置文本颜色

    # 间距&填充定义为字体大小的一小部分
    borderpad=None,      # 图例边框内的空白
    labelspacing=None,   # 图例条目之间的垂直间距
    handlelength=None,   # 图例手柄的长度
    handleheight=None,   # 图例手柄的高度
    handletextpad=None,  # 图例手柄和文本之间的填充
    borderaxespad=None,  # 轴和图例边框之间的填充
    columnspacing=None,  # 柱间距

    ncols=1,     # 列数
    mode=None,  # 列的水平分布:无或“展开”

    fancybox=None,  # True:花式框,False:圆形框,None:rcParam
    shadow=None,
    title=None,           # 图例标题
    title_fontsize=None,  # 图例标题字体大小
    framealpha=None,      # 设置帧alpha
    edgecolor=None,       # 边框补丁边缘颜色
    facecolor=None,       # 框架补丁面颜色

    bbox_to_anchor=None,  # 图例将锚定到的bbox
    bbox_transform=None,  # 为bbox转换
    frameon=None,         # 并条机
    handler_map=None,
    title_fontproperties=None,  # 图例标题的属性
    alignment="center",       # 控制图例框内的对齐
    ncol=1,  # ncols的同义词(向后兼容性)
    draggable=False  # 是否可以用鼠标拖动图例
):

  matplotlib条形图例子1

import matplotlib.pyplot as plt

a = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士",
     "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归",
     "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺",
     "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2",
     "情圣", "新木乃伊"]
b = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61,
     11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32, 6.99,
     6.88, 6.86, 6.58, 6.23]

plt.figure(figsize=(20, 10))

# 绘制条形图
plt.barh(range(len(a)), b, height=0.6, color='#FF6600')
plt.xticks(fontproperties='Times New Roman', fontsize=25)
plt.yticks(range(len(a)), a, fontproperties='SimSun', fontsize=15, rotation=45)
plt.xlabel("票房", fontsize=25, fontproperties='SimSun')  # x轴标签
plt.ylabel("电影名称", fontsize=25, fontproperties='SimSun')  # y轴标签

# 设置图表标题
plt.title("某年度电影票房排行榜", fontproperties='SimSun', fontsize=30)
# plt.legend(loc="upper left", prop='Times New Roman', fontsize=25, ncols=2, edgecolor='#C4C4C4',
#            facecolor='white', fancybox=True, title_fontsize=25)
plt.savefig("./14.png", dpi=1500)  # 保存图片
plt.show()

  matplotlib条形图例子2

import matplotlib.pyplot as plt

a = ["北京各区房价", "上海各区房价", "深圳各区房价", "鹤岗各区房价"]
b1 = [121000, 140885, 71219, 1948]
b2 = [148833, 116770, 106410, 2518]
b3 = [96384, 126999, 102957, 1720]
b4 = [88704, 121743, 58809, 1554]
b5 = [70884, 117869, 49275, 1239]
bar_width = 0.1

x1 = list(range(len(a)))
x2 = [i + bar_width for i in x1]
x3 = [i + bar_width * 2 for i in x1]
x4 = [i + bar_width * 3 for i in x1]
x5 = [i + bar_width * 4 for i in x1]

plt.figure(figsize=(20, 8))
plt.bar(range(len(a)), b1, width=bar_width, label="区1房价", color='#4A7EBB')
plt.bar(x2, b2, width=bar_width, label="区2房价", color='#FF6600')
plt.bar(x3, b3, width=0.1, label="区3房价", color='#00FF00')
plt.bar(x4, b4, width=0.1, label="区4房价", color='#C760FF')
plt.bar(x5, b5, width=0.1, label="区5房价", color='#02CCFE')

plt.rcParams.update({'font.size': 18})
plt.legend(prop='SimSun', fontsize=25)
plt.grid(alpha=0.5)
plt.xticks(x3, a, fontproperties='SimSun', fontsize=20)
plt.yticks(fontproperties='Times New Roman', fontsize=20)
plt.savefig("./15.png", dpi=1200)
plt.show()

matplotlib散点图例子

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimSun']
y1 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17,
    18, 21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23]
y2 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17,
    20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6]
x1 = range(1, 32)
x2 = range(51, 82)

# 设置图形大小
plt.figure(figsize=(20, 13))

plt.scatter(x1, y1, label="3月份", linewidth=10, color='#00FF00')
plt.scatter(x2, y2, label="10月份", linewidth=10, color='r')

# 调整x轴的刻度
_x = list(x1) + list(x2)
_xticks_labels = ["3月{}日".format(i) for i in x1]
_xticks_labels += ["10月{}日".format(i) for i in x2]

plt.xticks(_x[::3], _xticks_labels[::3], fontproperties='SimSun', rotation=45, fontsize=20)
plt.yticks(fontproperties='SimSun', fontsize=20)

# 添加图例
plt.legend(loc='upper left', fontsize=25)
# plt.grid(alpha=0.2)
# 添加描述信息
plt.xlabel("时间", fontproperties='SimSun', fontsize=25)
plt.ylabel("温度", fontproperties='SimSun', fontsize=25)
plt.title("气温与月份之间的关系", fontproperties='SimSun', fontsize=30, fontweight='bold')

plt.savefig("./12.png", dpi=1200)
plt.show()

 matplotlib误差棒例子1

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Times New Roman'
# 平均收入, 波动范围
money = [20, 25, 18, 22, 17, 15]
tolerance_p = [2, 1, 3, 4, 2, 1]

index = np.arange(len(money))
width = 0.4
cities = ['北京', '上海', '广州', '深圳', '西安', '武汉']
# 绘制房价柱状图和收入柱状图
# yerr用来指定误差范围, 与结果图中的误差线对应
err_attr = {"elinewidth": 2, "ecolor": "black", "capsize": 5}  # 误差棒的属性

bar_money = plt.bar(index, money, width, color=['#66FF33', '#00FFFF', '#FF00FF', '#FF6600', '#9900CC', '#0000FF'],
                     yerr=tolerance_p, error_kw=err_attr)

plt.xlabel('城市名称', fontproperties='simsun', fontsize=16)
plt.ylabel('金额(万元)', fontproperties='simsun', fontsize=16)
plt.title('收入与偏差关系', fontproperties='simsun', fontsize=22)
plt.xticks(index, cities, fontproperties='simsun', fontsize=15)

# 创建图例
def add_text(bars, tol):
    for index, bar in enumerate(bars):
        x = bar.get_x() + width/2
        h = bar.get_height()
        # 在每个柱的误差线上下两侧显示文本, ha、va表示水平、垂直对其方式
        plt.text(x, h+tol[index], str(h+tol[index]), color='k', ha='center', va='bottom', fontsize=9)
        plt.text(x, h-tol[index]-1, str(h-tol[index]), color='w', ha='center', va='bottom', fontsize=9)

add_text(bar_money, tolerance_p)
plt.savefig("D://matplotlib画图//学习//8_1.png", dpi=1800)
plt.show()

 matplotlib误差棒例子2

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Times New Roman']
x = (25, 26, 27, 28, 29)  # 年龄(岁)
y = (25, 26, 28, 30, 35)  # 年收入(万元)
y_offset = (3, 1, 2, 3, 3)  # 收入波动范围

# elinewidth=2(误差棒中间线的宽度)  capthick=1(上下两条横线的厚度)  capsize=5(上下两条横线的长度)
plt.errorbar(x, y, yerr=y_offset, capsize=5, capthick=1, linestyle='--', marker='*', markersize=15,
             color='#FF0000', linewidth=3, ecolor='#00FF00', elinewidth=2, barsabove=False)

# 在误差线上下两侧显示文本,ha、va表示水平、垂直对齐方式
for i, (xi, yi, offset) in enumerate(zip(x, y, y_offset)):
    plt.text(xi, yi + offset + 0.1, f'{yi + offset}', ha='center', va='bottom', fontsize=10, color='black')
    plt.text(xi, yi - offset - 0.3, f'{yi - offset}', ha='center', va='top', fontsize=10, color='black')

plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.xlabel('年龄(岁)', fontproperties='SimSun', fontsize=15)
plt.ylabel('年收入(万元)', fontproperties='SimSun', fontsize=15)
plt.title('年收入与年龄关系图', fontproperties='SimSun', fontsize=15)
plt.savefig("D://matplotlib画图//学习//9.png", dpi=1800)
plt.show()

你可能感兴趣的:(小工具,python,开发语言)