matplotlib画图并设置风格

https://github.com/garrettj403/SciencePlots

Demo

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib
matplotlib.matplotlib_fname()

def model(x, p):
    return x ** (2 * p + 1) / (1 + x ** (2 * p))

plt.style.available
['Solarize_Light2',
 '_classic_test_patch',
 'bmh',
 'bright',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'grid',
 'high-contrast',
 'high-vis',
 'ieee',
 'light',
 'muted',
 'no-latex',
 'notebook',
 'pgf',
 'retro',
 'scatter',
 'science',
 'seaborn',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark',
 'seaborn-dark-palette',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'std-colors',
 'tableau-colorblind10',
 'vibrant']
# -- coding: gbk --

x = np.array( [0, 15, 20, 25, 30, 35, 40, 45])

with plt.style.context(['no-latex']):
    pred = np.array([[53.71, 55.41, 55.86, 56.15, 56.92, 55.65, 56.80, 55.31],
                     [59.30, 60.92, 62.76, 63.72, 65.76, 65.37, 64.44, 63.63],
                     [75.90, 77.26, 77.61, 78.12, 78.64, 78.57, 78.03, 77.97],
                     [32.46, 36.20, 36.93, 37.62, 39.02, 38.29, 37.97, 36.47]
             ])
    styles = [':', '-', '--', '-.']
    for p, style in zip(pred, styles):
        plt.plot(x, p, label=x, linestyle=style, linewidth=2.5)
    
    #定义自定义字体,文件名从1.b查看系统中文字体中来
    myfont = matplotlib.font_manager.FontProperties(fname='/home/zjdou/anaconda3/envs/Pytorch/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf')
    #解决负号'-'显示为方块的问题
#     matplotlib.rcParams['axes.unicode_minus']=False
#     plt.title(u'中文', fontproperties=myfont, fontdict={'weight':'normal','size': 20})
#     plt.title(u'模型在不同遮蔽比例下的表现')

    plt.grid(True)
    plt.tight_layout()
    
    import matplotlib.ticker as mticker 
    plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f %%'))
    plt.legend(['COM.', 'CON.', 'EXP.', 'TEM.'], loc='upper center', bbox_to_anchor=(0.5, -0.1),fancybox=False, shadow=False, ncol=4)
    
    plt.show()

折线图

  • 数据样式
Year BLEU METEOR ROUGE CIDER
2016 2 1 0 0
2017 2 1 0 0
2018 4 1 2 1
2019 8 3 3 1	
2020 14 9 4 1
2021 8 4 6 0
with plt.style.context(['grid']):
    
    styles = [':', '-', '--', '-.']
    for d, s in zip(data.columns[1:], styles):
        plt.plot(data['Year'], data[d], label=data[d], linestyle=s, linewidth=1.5)
    
    #定义自定义字体,文件名从1.b查看系统中文字体中来
    myfont = matplotlib.font_manager.FontProperties(fname='/home/zjdou/anaconda3/envs/Pytorch/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf')
    #解决负号'-'显示为方块的问题
#     matplotlib.rcParams['axes.unicode_minus']=False
#     plt.title(u'中文', fontproperties=myfont, fontdict={'weight':'normal','size': 20})
#     plt.title(u'模型在不同遮蔽比例下的表现')

    plt.grid(True)
    plt.tight_layout()
    
    import matplotlib.ticker as mticker 
    plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f'))
    plt.legend(['BLEU', 'METEOR', 'ROUGE', 'CIDER'], loc='upper center', bbox_to_anchor=(0.5, -0.1),fancybox=False, shadow=False, ncol=4)
#     plt.legend(['BLEU', 'METEOR', 'ROUGE', 'CIDER'])
    
#     plt.savefig('plot2.pdf')

    
    plt.show()

扇形图

import matplotlib.ticker as mticker 

with plt.style.context(['no-latex']):
    
    #定义自定义字体,文件名从1.b查看系统中文字体中来
    myfont = matplotlib.font_manager.FontProperties(fname='/home/zjdou/anaconda3/envs/Pytorch/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf',
                                                   size=15)
    #解决负号'-'显示为方块的问题
#     plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
    matplotlib.rcParams['axes.unicode_minus']=False
    
    size = [2189+3789+7844, 685]
    lables=[u'Others', u'Temporal']
    explode=[0, 0]
    
    ax = plt.pie(size, explode=explode, labels=lables, labeldistance=1.05, autopct='%1.1f%%',
                 textprops= {'fontsize':14, 'color':'w'},
                 shadow=False, startangle=65, pctdistance=0.6)
    # ax[0]: patches
    # ax[1]: l_texts: 饼图外label的文本设置
    # ax[2]: p_texts: 饼图内部文本设置
    for font in ax[1]:
        font.set_fontproperties({'weight':'normal','size': 14})
        font.set_color('black')
        
    
    plt.axis('equal')  # 坐标一致,才能是圆形
    plt.title(u'饼图', fontproperties=myfont, fontdict={'weight':'normal','size': 45})

#     plt.grid(True)
    plt.tight_layout()
    
    plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f')) 
    
    # 图例字体设置
    font1 = {'family' : 'Times New Roman',
            'weight' : 'normal',
            'size'   : 14,
    }
#     plt.legend(loc='lower left', 
#                bbox_to_anchor=(0.75, 0.75), fancybox=False, shadow=False, ncol=1,
#                prop=font1)
    plt.legend(loc='upper left', 
               bbox_to_anchor=(0.20, 0.04), fancybox=False, shadow=False, ncol=2,
               prop=font1)
#     plt.legend(loc='lower right', 
#                bbox_to_anchor=(0.3, -0.05), fancybox=False, shadow=False, ncol=2,
#                prop=myfont)
    
    plt.show()

柱状图

# -- coding: gbk --

import numpy as np

with plt.style.context(['grid']):
    pred = np.array([36.47, 38.60, 38.94, 41.66])
    
    x = range(len(pred))
    labels = ['2018', '2019', '2020', '2021']
    plt.bar(x, pred-33, tick_label=labels, width=0.4, bottom=33)
#     plt.bar()
#     plt.yticks()
    
    #定义自定义字体,文件名从1.b查看系统中文字体中来
    myfont = matplotlib.font_manager.FontProperties(fname='/home/zjdou/anaconda3/envs/Pytorch/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf')
    #解决负号'-'显示为方块的问题
#     matplotlib.rcParams['axes.unicode_minus']=False
#     plt.title(u'中文', fontproperties=myfont, fontdict={'weight':'normal','size': 20})
#     plt.title(u'模型在不同遮蔽比例下的表现')
    
    plt.grid(True)
#     plt.tight_layout()
    
    import matplotlib.ticker as mticker 
    plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f %%'))
#     plt.legend(['COM.', 'CON.', 'EXP.', 'TEM.'], loc='upper center', bbox_to_anchor=(0.5, -0.1),fancybox=False, shadow=False, ncol=4)
    
    plt.show()

posted @ 2021-07-05 20:05  douzujun  阅读(434)  评论(0编辑  收藏  举报