记Matplotlib科学绘图包使用心得

内容

双坐标绘图

def plot_compare2():
    n = 200
    fig = plt.figure()
    requests = Counter(generateRequestData(n))
    sortedKeys = sorted(requests)

    ax1 = fig.add_subplot(111)
    content_property = mzipf(25, 0.8, n, False)
    content_rank = [i for i in range(len(content_property))]
    ax1.set_xlabel("Content popularity rank", fontsize=12)
    ax1.set_ylabel('Probability of content being requested', fontsize=12)

    ax1.plot(content_rank, content_property, 'r', marker='.', label="Mzipf(25,0.8)")

    # 双坐标绘图
    ax2 = ax1.twinx()
    x = sortedKeys
    y = [Counter(requests)[i] for i in sortedKeys]
    ax2.bar(x, y, label="Real content requests distribution")
    ax2.set_ylabel("The number of times the content was requested", fontsize=12)
    fig.legend(bbox_to_anchor=(18 / 20, 12 / 14), fontsize=12)

    plt.savefig("MZipf_fit")
    plt.show()

效果
在这里插入图片描述

设置字体大小和格式

def plot_compare_fig(*kwargs, mode="subplot"):
    file = dict(kwargs)
    fig_nums = file.keys()
    # 子图对比
    figure, ax = plt.subplots(figsize=(12, 8))
    # 设置坐标刻度大小和字体
    plt.tick_params(labelsize=15)
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 设置横纵坐标的名称以及对应字体格式
    font_axis = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 18,
             }
    if mode == "subplot":
        for n in fig_nums:
            plt.subplot(1, len(fig_nums), n)
            plot_user_model_accuracy(file[n])
    if mode == "one_fig":
        for n in fig_nums:
            history = pd.read_csv(file[n], header=None).to_numpy().reshape(10, )
            x = np.array([i + 1 for i in range(history.shape[0])])
            plt.xlabel("Identifications of IDs' model", font_axis)
            plt.ylabel("Prediction accuracy", font_axis)
            plt.bar(x + ((n - 1.5) * 0.3), history, width=0.3)
            plt.ylim(0, 1)
            y_major_locator = MultipleLocator(0.1)
            ax = plt.gca()
            ax.yaxis.set_major_locator(y_major_locator)
            # plt.xticks(x, ['mod %d' % (i+1) for i in range(history.shape[0])], rotation=45)
            plt.xticks(x, [(i + 1) for i in range(history.shape[0])])

    # 设置图例并且设置图例的字体及大小
    font_legend = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 20,
             }
    plt.legend(['C-DNN', 'D-DNN', 'CUPE'], prop=font_legend)
    foo_fig = plt.gcf()  # 'get current figure'
    foo_fig.savefig("accuracy_compare.eps", format='eps', dpi=1000, bbox_inches='tight')
    plt.show()

核心代码:

	 # 设置坐标刻度大小和字体
	plt.tick_params(labelsize=15)
	labels = ax.get_xticklabels() + ax.get_yticklabels()
	[label.set_fontname('Times New Roman') for label in labels]
	# 设置横纵坐标的名称以及对应字体格式
    font_axis = {'family': 'Times New Roman',
                 'weight': 'normal',
                 'size': 18,
                 }
    plt.xlabel("Identifications of IDs' model", font_axis)
    plt.ylabel("Prediction accuracy", font_axis)             
    # 设置图例并且设置图例的字体及大小
    font_legend = {'family': 'Times New Roman',
                   'weight': 'normal',
                   'size': 20,
                   }
    plt.legend(['C-DNN', 'D-DNN', 'CUPE'], prop=font_legend)               

设置为紧凑显式图片以及保存为eps格式

matplotlib 及其他一些画图工具,在保存plot的时候,总会出现一些问题,例如图片周边包含多余空白区域。这里主要解决这个问题.

foo_fig = plt.gcf()  # 'get current figure'
foo_fig.savefig("accuracy_compare.eps", format='eps', dpi=1000, bbox_inches='tight')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值