当前位置:网站首页>Matplotlib, set coordinate scale size, font / set legend size and font / set vertical and horizontal coordinate name, font and size
Matplotlib, set coordinate scale size, font / set legend size and font / set vertical and horizontal coordinate name, font and size
2022-06-11 07:06:00 【Boiled wine cos】
Basic drawing case
# coding: utf-8
import matplotlib.pyplot as plt
# figsize = 11, 9
# figure, ax = plt.subplots(figsize = figsize)
x1 =[0,5000,10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000]
y1=[0, 223, 488, 673, 870, 1027, 1193, 1407, 1609, 1791, 2113, 2388]
x2 = [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000]
y2 = [0, 214, 445, 627, 800, 956, 1090, 1281, 1489, 1625, 1896, 2151]
# Set the size of the output picture
figsize = 11, 9
figure, ax = plt.subplots(figsize=figsize)
# Draw two broken lines on the same picture
A, = plt.plot(x1, y1, '-r', label='A', linewidth=5.0)
B, = plt.plot(x2, y2, 'b-.', label='B', linewidth=5.0)
# Set the legend and set the font and size of the legend
font1 = {
'family': 'Times New Roman',
'weight': 'normal',
'size': 23,
}
legend = plt.legend(handles=[A, B], prop=font1)
# Set the size of the coordinate scale value and the font of the scale value
plt.tick_params(labelsize=23)
labels = ax.get_xticklabels() + ax.get_yticklabels()
# print labels
[label.set_fontname('Times New Roman') for label in labels]
# Set the name of the horizontal and vertical coordinates and the corresponding font format
font2 = {
'family': 'Times New Roman',
'weight': 'normal',
'size': 30,
}
plt.xlabel('round', font2)
plt.ylabel('value', font2)
plt.show()
python- increase matplotlib The line width of the routine in the figure
That's true. , If you change the line width , Will be automatically updated in the legend . however , I just want to change the lineweight of the legend without affecting the drawing .
There are now four solutions
obtain leg object
# This is a simple example :
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
p1 = plt.plot(x, y1, 'b-', linewidth=1.0)
p2 = plt.plot(x, y2, 'r-', linewidth=1.0)
# make a legend for both plots
leg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1)
# set the linewidth of each legend object
for legobj in leg.legendHandles:
legobj.set_linewidth(2.0)
plt.show()
pyplot Provided api
@Brendan Wood The method of using pyplot Provided api. stay matplotlib in , Object oriented styles that use axes are preferred . Here's how to use axes Methods methods to achieve this .
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y1, linewidth=1.0, label='sin(x)'
ax.plot(x, y2, linewidth=1.0, label='cos(x)')
leg = ax.legend()
for line in leg.get_lines():
line.set_linewidth(4.0)
plt.show()
Custom scheme
If you want to change all the lines in the drawing , It might be useful to define your own legend handlers :
import matplotlib.pyplot as plt
from matplotlib import legend_handler
from matplotlib.lines import Line2D
import numpy as np
class MyHandlerLine2D(legend_handler.HandlerLine2D):
def create_artists(self, legend, orig_handle,xdescent, ydescent, width, height, fontsize,trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,width, height, fontsize)
ydata = ((height-ydescent)/2.)*np.ones(xdata.shape, float)
legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend)
#legline.update_from(orig_handle)
#legend._set_artist_props(legline) # after update
#legline.set_clip_box(None)
#legline.set_clip_path(None)
legline.set_drawstyle('default')
legline.set_marker("")
legline.set_linewidth(10)
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(legline_marker, orig_handle, legend)
#legline_marker.update_from(orig_handle)
#legend._set_artist_props(legline_marker)
#legline_marker.set_clip_box(None)
#legline_marker.set_clip_path(None)
legline_marker.set_linestyle('None')
if legend.markerscale != 1:
newsz = legline_marker.get_markersize()*legend.markerscale
legline_marker.set_markersize(newsz)
# we don't want to add this to the return list because
# the texts and handles are assumed to be in one-to-one
# correpondence.
legline._legmarker = legline_marker
return [legline, legline_marker]
plt.plot( [0, 1], [0, 1], '-r', lw=1, label='Line' )
plt.legend(handler_map={
Line2D:MyHandlerLine2D()})
plt.show()
Use a copy of the artist on the canvas
By default , The legend contains the row itself . therefore , Changing the lineweight of the lines in the canvas also changes the lines in the legend ( vice versa , Because they are essentially the same object ).
One possible solution is to use a copy of the artist on the canvas , And only change the lineweight of the copy .
import numpy as np
import matplotlib.pyplot as plt
import copy
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
ax.plot(x, y2, c='r', label='y2')
# obtain the handles and labels from the figure
handles, labels = ax.get_legend_handles_labels()
# copy the handles
handles = [copy.copy(ha) for ha in handles ]
# set the linewidths to the copies
[ha.set_linewidth(7) for ha in handles ]
# put the copies into the legend
leg = plt.legend(handles=handles, labels=labels)
plt.savefig('leg_example')
plt.show()
Use handler_map And update functions
Another option is to use handler_map And update functions . This is automatic in some way , Specifies that the handler mapping will automatically make any row width in the legend 7 spot .
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
ax.plot(x, y2, c='r', label='y2')
linewidth=7
def update(handle, orig):
handle.update_from(orig)
handle.set_linewidth(7)
plt.legend(handler_map={
plt.Line2D : HandlerLine2D(update_func=update)})
plt.show()
The result is the same as above .
边栏推荐
- 迅为干货 |瑞芯微RK3568开发板TFTP&NFS烧写(上)
- Duality-Gated Mutual Condition Network for RGBT Tracking
- 洛谷P1091合唱队形(最长上升子序列)
- Difference between byte and bit
- byte和bit的区别
- 【Matlab印刷字符识别】OCR印刷字母+数字识别【含源码 1861期】
- 一、SQLServer2008安装(带密码)、创建数据库、C#窗体项目测试
- Atom, the top stream editor, will leave the historical stage on December 15
- Start the Nacos server of shell script
- Latex various arrows / arrows with text labels / variable length arrows
猜你喜欢

Education expert wangzhongze solves students' problems with one move
![Error occurred in pycharm DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])](/img/1c/4013479ce1fc5b0ff2ebeb754f05a9.png)
Error occurred in pycharm DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])

During unity panoramic roaming, AWSD is used to control lens movement, EQ is used to control lens lifting, and the right mouse button is used to control lens rotation.

开源漫画服务器Mango

Menu double linkage effect in uniapp
![pycharm出现error.DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])](/img/1c/4013479ce1fc5b0ff2ebeb754f05a9.png)
pycharm出现error.DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])

Shuttle container component

WPF 数据绑定(四)

Records how cookies are carried in cross domain requests

Analysis of key points and difficulties of ES6 promise source code
随机推荐
latex 各种箭头/带文字标号的箭头/可变长箭头
一、SQLServer2008安装(带密码)、创建数据库、C#窗体项目测试
About the designer of qtcreator the solution to the problem that qtdesigner can't pull and hold controls normally
Detailed explanation of mutationobserver
Bat (batch processing) processing special symbols (exclamation point, percent sign), etc
1300. the array closest to the target value after transforming the array and
生物序列智能分析平台blog(1)
Matplotlib,设置坐标刻度大小,字体/设置图例大小及字体/设置纵横坐标名称及字体及大小
First day of database
Check whether the filing information of the medical representative is correct
Practice: how to reasonably design functions to solve practical problems in software development (II) -- improving reusability
webserver
WPF 数据绑定(四)
SQL language - query statement
常用问题排查工具和分析神器,值得收藏
This comprehensive understanding
Common troubleshooting tools and analysis artifacts are worth collecting
pycharm出现error.DeprecatedEnv: Env FrozenLake-v0 not found (valid versions include [‘FrozenLake-v1‘])
Library management system 2- demand analysis
资深OpenStacker - 彭博、Vexxhost升级为OpenInfra基金会黄金成员