当前位置:   article > 正文

【Python绘图技巧大合集】_python制图很丑怎么办

python制图很丑怎么办

1、调整图片清晰度

(1)调整dpi值,越高越清晰。

bbox_inches参数可以使全图完整输出

例:plt.savefig(“图.png”, dpi=750, bbox_inches = ‘tight’)

(2)如果在jupyter notebbok或者jupyter lab中输出的图像,可以使用下面的程序控制输出图像的清晰度。

## 输出高清图像
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
#retina是在Mac os系统下的通常设置,也可以改为png等格式的图像。
  • 1
  • 2
  • 3
  • 4

2、支持中文字体设置

matplotlib默认的字体并不支持中文。
在使用中文时,我们需要将字体修改为支持中文的字体,比如常见的宋体,黑体等。
那么下一个问题又来了,如何才能知道系统有哪些字体呢?或者更直接一点,matplotlib可以使用的字体有哪些呢?
答案是可以使用matplotlib中的font_manager查询。代码如下:

import matplotlib
font_list = matplotlib.font_manager.fontManager.ttflist
for font in font_list:
    if ('Song' in font.name) or ('Hei' in font.name):
        print(font.name)
  • 1
  • 2
  • 3
  • 4
  • 5

结果如下:

Microsoft YaHei
FangSong
Microsoft JhengHei
Adobe Heiti Std
FZCuHeiSongS-B-GB
STSong
Microsoft JhengHei
Microsoft JhengHei
SimHei
Microsoft YaHei
Adobe Song Std
Microsoft YaHei
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

设置上述字体:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([4, 3, 2, 1, 4])
plt.bar(x, y)
plt.title('这是标题', font={'family':'SimHei'})
plt.ylabel('这是纵坐标标题', font={'family':'STSong'})
plt.xlabel('这是横坐标标题', font={'family':'STSong'})
plt.savefig("./pics/字体设置.png", dpi=750, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

中文字体

3、特殊符号的latex语法支持

matplotlib自带latex的语法支持,下面以插入, 和分数1/2示例,代码如下:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
matplotlib.rc('font', family = 'Microsoft YaHei', size = 10)#, weight = 'bold'
x = np.array([0, 1, 2, 3, 4])
y = np.array([4, 3, 2, 1, 4])
plt.bar(x, y)
plt.title(r'Example of $\frac{1}{2}$')
plt.ylabel(r'Example of $\beta$')
plt.xlabel(r'Example of $\alpha$')
plt.savefig("./pics/公式字符.png", dpi=750, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

latex支持

4、调整标题位置和角度

上述三个标题函数了自带了loc参数,可以实现简单的left/botton, center和right/top的设置。至于角度,可以使用rotation参数设置。代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([4, 3, 2, 1, 4])
plt.bar(x, y)
plt.title('This is the title', font={'family':'Arial', 'size':18}, loc='left')
plt.ylabel('This is the y-axis label', font={'family':'Arial', 'size':16}, loc='top')
plt.xlabel('This is the x-axis label', font={'family':'Arial', 'size':16}, rotation=10)
plt.savefig("./pics/位置角度.png", dpi=750, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

位置和角度

5、使用颜色名称指定颜色

例如,使用plt.bar()中的color参数将柱子的颜色改为灰色,代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='gray')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

指定颜色
查看颜色缩写,参考:https://zhuanlan.zhihu.com/p/586935440

import matplotlib.colors as mcolors
print(mcolors.BASE_COLORS.keys())
  • 1
  • 2

输出结果:

dict_keys(['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'])
  • 1

基本色

查看所有颜色名也可以在matplotlib.mcolors中查到

import matplotlib.colors as mcolors
print(mcolors.CSS4_COLORS.keys())
  • 1
  • 2

所有色

6、使用十六进制RGB值制定颜色

有一些场景对颜色有着严格的要求,可能需要精确地用RGB值来表示。
上述函数中的color参数可以直接输入十六进制的RGB值,前两个数表示Red分量,中间两个数表示Green分量,最后两个数表示Blue分量。
下面展示一个使用十六进制数表示颜色的例子,代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color=['#808080', '#00008B', '#B22222', '#90EE90', '#FF69B4']) 
# [grey, darkblue, firebrick, lightgreen, hotpink]
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

16进制色
在上面的代码中,我在注释里标上了每一种颜色的颜色名,
给大家推荐一种方便地知道每种颜色十六进制值的办法,还是使用matplotlib.mcolors。代码如下:

import matplotlib.colors as mcolors
print(mcolors.CSS4_COLORS['hotpink']) # [grey, darkblue, firebrick, lightgreen, hotpink]
  • 1
  • 2

输出:#FF69B4

7、渐变色设置

渐变色

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
print(np.arange(x.shape[0]))
my_colors = cm.Greens_r(np.arange(x.shape[0]) / x.shape[0])
plt.bar(x, y, color=my_colors)
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述

7、图片保存格式设置

参考:https://zhuanlan.zhihu.com/p/592141461

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='r')
plt.savefig('pics/savefig_example.png')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

图片格式
在写论文时,我们往往需要绘制eps格式的矢量图,plt.savefig()也是可以直接存的:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='g')
plt.savefig('pics/savefig_example.eps') 
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

eps格式

8、分辨率的修改

为了获得高分辨率的图片,我们需要使用dpi参数,
dpi是dots per inch的缩写,也就是,dpi越大,每单位长度的点越多,意味着图片的分辨率越高。
举个例子,我们把dpi设为300,代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='c')
plt.savefig('pics/savefig_example_dpi.png', dpi=300)
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

dpi高精度

9、图框的调整

当我们进行了一些复杂的设置时,导出的图片可能会残缺不全。
举个例子,将x轴标题旋转了10度:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='g')
plt.xlabel('This is the x-axis label', rotation=10)
plt.savefig('pics/savefig_example_rotate.png')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

旋转不全
发现x轴的标题少了一半!这是因为我们并没有调整画布,x轴标题本来就已经在画布最下面了,一转就转出去了。
将bbox_inches参数设置为’tight’就可以解决这个问题了,这个参数的意思是指定要导出的图框位置,
设置为tight可以理解为自适应地找到一个能包含所有元素的框,代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='g')
plt.xlabel('This is the x-axis label', rotation=10)
plt.savefig('pics/savefig_example_rotate1.png', bbox_inches='tight')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

旋转补全

10、图框背景颜色设置

matplotlib画出的图,边框背景默认是白色,有时候我们想要更换边框背景的颜色,
让数据图显得专业一些,可以用facecolor这个参数来实现。代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='g')
plt.savefig('pics/savefig_example_facecolor.png', facecolor='grey')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

背景修改

11、透明度设置

在python中画的图只是一张大图的一个小部分,这时候画的图最好是背景透明的,这样在拼接的时候不容易遮挡到其他的图。
透明的背景可以用transparent这个参数来实现,代码如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([5, 4, 3, 2, 1])
plt.bar(x, y, color='g')
plt.savefig('pics/savefig_example_trans_true.png', transparent=True)
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

无背景,两图堆叠无背景

12、绘制折线图

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc('font', family = 'Times New Roman')#, weight = 'bold'
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)
plt.plot(x, y,color ='c', linewidth = 2, linestyle = 'dashdot')
plt.savefig("./pics/1.png", dpi=750, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
# plt.savefig("./pics/1_1.png")
# plt.savefig("./pics/1_2_dpi750.png",dpi=750)
plt.show()
print(matplotlib.matplotlib_fname())    #查看字体路径
print(matplotlib.get_cachedir())    #查看字体缓存
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

输出:

d:\zhuanyeruanjian\Anaconda\envs\pytorch\lib\site-packages\matplotlib\mpl-data\matplotlibrc
C:\Users\Admin\.matplotlib
  • 1
  • 2

折线图
对散点图修饰

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc('font', family = 'Times New Roman')#

x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)

plt.plot(x,y,color = 'c', linewidth = 2,linestyle = 'dashdot',marker= '*',markersize= 10)
plt.savefig("./pics/1_3_eps.eps",dpi=750)
plt.savefig("./pics/1_3_svg.svg",dpi=750)
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

修饰标记

13、绘制面积图

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc('font', family = 'Times New Roman')#

x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)

plt.stackplot(x,y,color= 'c')
plt.savefig("./pics/面积图.png", dpi=750, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

面积图

14、绘制饼图

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)

plt.pie(y, labels= x, labeldistance = 1.1, autopct = '%.2f%%', pctdistance = 1.5)
plt.savefig("./pics/饼图.jpeg", dpi=1024, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

饼图

对饼图加以处理

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)
print(y)
# plt.pie(y, labels= x, labeldistance = 1.1, autopct = '%.2f%%', pctdistance = 1.5)
plt.pie(y, labels= x, labeldistance = 1.1, autopct = '%.2f%%', pctdistance = 1.5,explode=[0,0,0,0,0,0,0,0,0,0.3,0.5,0],startangle=90, counterclock=False)
plt.savefig("./pics/饼图1.jpeg", dpi=1024, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

饼图处理
不同形式的饼图,挖掉中间部分

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)
print(y)
plt.pie(y, labels= x, labeldistance = 1.1, autopct = '%.2f%%', pctdistance = 1.5,wedgeprops={'width':0.3,'linewidth':2 ,'edgecolor':'white'})
plt.savefig("./pics/饼图2.jpeg", dpi=1024, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

饼图挖空

15、大合成,四种图形形式

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(76,155,12)
print(y)
plt.subplot(2,2,1)
plt.pie(y, labels= x, labeldistance = 1.1, startangle=90, counterclock=False)

plt.subplot(2,2,2)
plt.bar(x,y, width = 0.5,color= 'r')

plt.subplot(2,2,3)
plt.stackplot(x, y, color= 'gray')

plt.subplot(2,2,4)
plt.plot(x,y,color='c',linestyle= 'solid',linewidth = 2,marker='o',markersize= 10)
plt.savefig("./pics/合成.jpeg", dpi=2048, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

合成

16、绘制气泡图

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
n = ['1','2','3','4','5','6','7','8','9','10','11','12']
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y = np.random.randint(1,20,12)
z = np.random.randint(1,20,12)
print(y)
print(z*100)
plt.scatter(x,y,s=z*100, color= 'c', marker='o')
for a, b, c in zip(x,y,n):
    plt.text(x=a, y=b, s=c, ha= 'center', va= 'center', fontsize=15, color='w')

plt.xlim(1, 12)
plt.ylim(1,20)
plt.savefig("./pics/气泡图.jpeg", dpi=1024, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

气泡图## 17、绘制组合图

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
#设置中文字体
matplotlib.rc("font",family = 'MicroSoft YaHei',weight = 'bold' )
x = ['1','2','3','4','5','6','7','8','9','10','11','12']
y1 = np.random.randint(76,155,12)
y2 = np.random.randint(76,155,12)
print(y1)
print(y2)
plt.bar(x,y1, width = 0.5,color= 'c')
plt.plot(x,y2,color='r',linestyle= 'solid',linewidth = 2,marker='o',markersize= 1)
plt.savefig("./pics/组合图.jpeg", dpi=1024, bbox_inches = 'tight') # bbox_inches参数可以使全图完整输出
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

组合图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/276578
推荐阅读
相关标签
  

闽ICP备14008679号