plt add legend/set axis scale

This article is a supplement to the python data analysis series-matplotlib from entry to abandonment .
For more articles, please see the blogger's article column.
Follow me, wonderful and uninterrupted!

1. Add a legend

When drawing multiple curves in the same graph, in order to facilitate the distinction and make the image more professional, we usually add a legend to the image.
as follows:

import matplotlib.pyplot as plt
import numpy as np

a = np.arange(10,40,2)
b = np.arange(40,70,2)

# 传入xy轴参数,默认为y轴;label 指定图例名称
plt.plot(a,label="a",color="blue")
plt.plot(b,label="b",color="green")

plt.legend(loc="upper left")  # 设置图例位置

# 指定xy轴 名称
plt.ylabel("This is Y")
plt.xlabel("This is X")

# 保存图像 默认png格式,其中dpi指图片质量
plt.savefig("05.png", dpi=600)

plt.show()  # 展示图片

The input image is as follows:
Insert picture description here
by specifying the legend name in plot(label=" "), and then specifying the position of the legend through the parameter of legend(), you can add a legend to the image, where the loc parameter is as follows:

  • best
  • upper right
  • upper left
  • lower left
  • lower right
  • right
  • center left
  • center right
  • lower center
  • upper center
  • center

2. Set the xy axis scale

We have described how to set the image legend above, but careful friends will find that when we set the image x/y axis coordinate scale, we let it automatically adjust, but sometimes we need to artificially control the scale. At this time we can set plt.xticks()/plt.yticks():

import matplotlib.pyplot as plt
import numpy as np

a = np.arange(10,100)
b = np.arange(40,130)

# 设置x/y轴尺度
plt.xticks(a[::5])
plt.yticks(b[::10])

# 传入xy轴参数,默认为y轴;label 指定图例名称
plt.plot(a,label="a",linestyle="--",color="blue")
plt.plot(b,label="b",color="green")

plt.legend(loc="best")  # 设置图例位置

# 指定xy轴 名称
plt.ylabel("This is Y")
plt.xlabel("This is X")

# 保存图像 默认png格式,其中dpi指图片质量
plt.savefig("05.png", dpi=600)

plt.show()  # 展示图片

The image is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45807032/article/details/108182806