Use python to draw a histogram (matplotlib.pyplot)--this graph basically includes the settings you want

I drew the picture when I wrote the thesis, and I will summarize the method: Read it with peace of mind, you should be able to draw a good-looking histogram, basically all the settings you need are there! ! !

Table of contents

1 First introduce the package Matplotlib required for drawing

2 Matplotlib Pyplot

3 Draw a histogram

4 overall code


1 First introduce the package Matplotlib required for drawing

Matplotlib is a plotting library for Python that allows users to easily visualize data and provide a variety of output formats.

Matplotlib can draw line plots, scatterplots, contour plots, bar charts, histograms, 3D graphics, even graphic animations, and more.

Matplotlib is commonly used with NumPy and SciPy (Scientific Python)

2 Matplotlib Pyplot

Pyplot is a sub-library of Matplotlib that provides a drawing API similar to MATLAB.

Pyplot is a commonly used drawing module, which makes it easy for users to draw 2D charts.

Import the pyplot library using import and set an alias plt:

import matplotlib.pyplot as plt

3 Draw a histogram

The histogram I drew here has the following settings: (should contain all the basic settings for drawing the histogram)

  • The border of the graph should be set to black, with a line width of 2;
  • The inside of the figure should contain grid lines;
  • The column in the histogram should also contain a border, and the color of the border is black;
  • The grid lines should be located below the columns;
  • The picture font should be set to 'Times New Roman', and the size of all fonts in the picture should be set;
  • The y-axis domain value should also be set, not starting from 0;
  • The label (icon) of the picture should be arranged horizontally (not vertically);
  • The specific value should be displayed above the column;
  • One label corresponds to multiple columns (for comparison)

The drawn picture shows:

(1) First, set the X-axis label and the y value corresponding to the X-axis label.

import matplotlib.pyplot as plt

# X轴标签
x = ['Data-15','Data-17','Data-18']

# 这里是一个标签对应两个柱子,所以有两个数组(这实际上是不同模型在同一数据集上的的f1值对比)
f1_1 = [93.70,92.17,84.89]
f1_2 = [95.76,93.35,89.20]

(2) To locate the starting position of the column (because the 3 X-axis labels are set above, so the starting position of the 3 columns should be located here)

x_len = np.arange(len(x))
total_width, n = 0.9, 3
width = total_width/n
# xticks 就是三个柱子的开始位置
xticks = x_len - (total_width - width) / 2

You can look at the corresponding values ​​of x_len and xticks :

x_len
Out[1]: array([0, 1, 2])
xticks
Out[2]: array([-0.3,  0.7,  1.7])

(3) Define the size of the picture and draw a grid for the picture

        The specific explanation is written in the code;

plt.figure(figsize=(15, 12), dpi=200)
# 这里定义ax,是为了后面画图的边框所用
ax = plt.axes()
# axis取值可以为'both','x','y', both是网格,x是只有垂直于x轴的线,y是只有垂直于yz轴的线
# c是设置线的颜色,linestyle 是画出的线的类型, zorder 是让线位于柱子下面而设置的,其值越小,线越靠下
plt.grid(axis="y", c='#d2c9eb', linestyle = '--',zorder=0)

(4) Start to draw the pillars, and set the attributes needed to draw the pillars

        Because each X-axis label corresponds to two columns, two plt.bars are called here;

        That is to say, call several plt.bars, and draw several columns for each x-axis label;

        For the explanation of specific attributes, see the comments in the code below;

# 画第一个柱子,是批量画的,X轴的每个标签都开始画第一个柱子
# f1_1就是X轴所有标签对应的第一个柱子的y值
# width是设置柱子的宽度
# label就是图例
# color设置颜色
# edgecolor是设置柱子框的颜色
# linewidth是设置柱子框的线宽
# zorder 是保证柱子位于网格线的上方

plt.bar(xticks, f1_1, width=0.9*width, label="Attention weights", color="#7e728c",edgecolor='black',linewidth = 2,  zorder=10)

# xticks + width,表示的是X轴所有标签第二个柱子的起始位置
plt.bar(xticks + width, f1_2, width=0.9*width, label="Official", color="#46513c",edgecolor='black',linewidth = 2, zorder=10)

(4) Add a value to the top of the column

        By the way, set the font of the number;


# 这是为X轴所有标签的第一个柱子写上值
# f1_1[0] + 0.3 表示写的值要距离柱子0.3个单位
# f1_1[0]是具体要写的值
# ha='center' 表示值要居中写
# fontproperties 是设置字体类型
# fontsize 设置字体大小
# zorder=10 表示位于网格线上方

plt.text(xticks[0], f1_1[0] + 0.3, f1_1[0], ha='center',fontproperties='Times New Roman',  fontsize=35,  zorder=10)
plt.text(xticks[1], f1_1[1] + 0.3, f1_1[1], ha='center', fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[2], f1_1[2] + 0.3, f1_1[2], ha='center', fontproperties='Times New Roman', fontsize=35,  zorder=10)

# 这是为X轴所有标签的第二个柱子写上值

plt.text(xticks[0] + width, f1_2[0] + 0.3, f1_2[0], ha='center',fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[1] + width, f1_2[1] + 0.3, f1_2[1], ha='center',fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[2] + width, f1_2[2] + 0.3, f1_2[2], ha='center', fontproperties='Times New Roman',fontsize=35,  zorder=10)

(5) Set the font of the legend

# ncol = 2 表示图例要放两列
plt.legend(prop={'family' : 'Times New Roman', 'size': 35}, ncol = 2)

(6) Set the font and size of the X-axis and Y-axis labels

# x_len表示X轴的标签写在哪个坐标位置,有事可能x_len有变差,需要手动调一下他的值,不过偏差不会很大
plt.xticks(x_len, x, fontproperties='Times New Roman',fontsize = 40)
plt.yticks(fontproperties='Times New Roman',fontsize = 40)

(7) Control the value of the Y axis

plt.ylim(75,90)
# 或者只设置最小值
plt.ylim(ymin=75)

(8) Set the description of the X-axis and Y-axis of the histogram

plt.xlabel("Datasets", fontproperties='Times New Roman',fontsize=45)
plt.ylabel("Accuracy (%)",fontproperties='Times New Roman', fontsize=45)

(9) Draw a black frame for the columnar graph

# 底部线
ax.spines['bottom'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['bottom'].set_color('black')
# 顶部线
ax.spines['top'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['top'].set_color('black')
# 右侧线
ax.spines['right'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['right'].set_color('black')
# 左侧线
ax.spines['left'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['left'].set_color('black')

(10) display diagram

plt.show()

4 overall code

You can copy all the code here and run the histogram above.

import json
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f1_1 = [93.70,92.17,84.89]
f1_2 = [95.76,93.35,89.20]

x = ['Data-15','Data-17','Data-18']
x_len = np.arange(len(x))
total_width, n = 0.9, 3
width = 0.3
xticks = x_len - (total_width - width) / 2
plt.figure(figsize=(15, 12), dpi=200)

ax = plt.axes()
plt.grid(axis="y", c='#d2c9eb', linestyle = '--',zorder=0)
plt.bar(xticks, f1_1, width=0.9*width, label="Attention weights", color="#92a6be",edgecolor='black',linewidth = 2,  zorder=10)
plt.bar(xticks + width, f1_2, width=0.9*width, label="Official", color="#c48d60",edgecolor='black',linewidth = 2, zorder=10)
plt.text(xticks[0], f1_1[0] + 0.3, f1_1[0], ha='center',fontproperties='Times New Roman',  fontsize=35,  zorder=10)
plt.text(xticks[1], f1_1[1] + 0.3, f1_1[1], ha='center', fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[2], f1_1[2] + 0.3, f1_1[2], ha='center', fontproperties='Times New Roman', fontsize=35,  zorder=10)

plt.text(xticks[0] + width, f1_2[0] + 0.3, f1_2[0], ha='center',fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[1] + width, f1_2[1] + 0.3, f1_2[1], ha='center',fontproperties='Times New Roman', fontsize=35,  zorder=10)
plt.text(xticks[2] + width, f1_2[2] + 0.3, f1_2[2], ha='center', fontproperties='Times New Roman',fontsize=35,  zorder=10)

plt.legend(prop={'family' : 'Times New Roman', 'size': 35}, ncol = 2)
x_len = [-0.1,0.9,1.9]
x_len = np.array(x_len)
plt.xticks(x_len, x, fontproperties='Times New Roman',fontsize = 40)
plt.yticks(fontproperties='Times New Roman',fontsize = 40)
plt.ylim(ymin=75)
plt.xlabel("Datasets", fontproperties='Times New Roman',fontsize=45)
plt.ylabel("Accuracy (%)",fontproperties='Times New Roman', fontsize=45)
ax.spines['bottom'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['top'].set_color('black')
ax.spines['right'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['right'].set_color('black')
ax.spines['left'].set_linewidth('2.0')#设置边框线宽为2.0
ax.spines['left'].set_color('black')

plt.show()

Guess you like

Origin blog.csdn.net/qq_40671063/article/details/127972727