[] Laboratory building /matplotlib.pyplot draw Cartesian coordinates + comments + Legend

I. Description of the problem

II. Analysis

Do this kind of problem we should first look roughly drawn map, and then consider the details.

Here is a difficult point plotted Cartesian coordinate system, as we default are used in FIG rectangular coordinate system of.

To sum up a little, so probably it can be divided into steps to go:

  1.  Cartesian coordinate system to draw
  2.  Draw two trigonometric functions
  3.  Draw two lines
  4.  Draw annotation
  5. Draw Legend

Now, I realize it step by step.

 

III. Drawing Cartesian coordinates

Here I introduce two methods.

The first modified directly on a histogram of. Mainly the above two to the right and to the wipe in addition to the rectangular boundary.

# 在这里我不得不吐槽matplotlib的官方文档做的实在是太不好了
# 很多api都只有声明和源码,没有具体的解释
# 想要找到具体的用法只能是在网上找博客
import numpy as np
import matplotlib.pyplot as plt

# 创建画板和画布对象
plt.figure(figsize=(8, 5), dpi=80)
ax = plt.subplot(111)

# 这次不整个消失了
# 我们选择将右边及上面的矩形边框删除掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 设置坐标轴上数据的方向
# 0是和我们普通笛卡尔坐标系相一致的,1则是相反的
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

The second is to use mpl_axisartist. This module is specifically used to draw axis.

Its function is very powerful, you can also add the positive direction of the arrow to our axes . Add some comments ah whatever.

import numpy as np #导入数值计算模块
import matplotlib.pyplot as plt #导入绘图模块
import mpl_toolkits.axisartist as axisartist #导入坐标轴加工模块

fig=plt.figure() #新建画布
ax=axisartist.Subplot(fig,111) #使用axisartist.Subplot方法创建一个绘图区对象ax
fig.add_axes(ax) #将绘图区对象添加到画布中

ax.axis[:].set_visible(False) #隐藏原来的实线矩形

ax.axis["x"]=ax.new_floating_axis(0,0,axis_direction="bottom") #添加x轴
ax.axis["y"]=ax.new_floating_axis(1,0,axis_direction="bottom") #添加y轴

ax.axis["x"].set_axisline_style("->",size=1.0) #给x坐标轴加箭头
ax.axis["y"].set_axisline_style("->",size=1.0) #给y坐标轴加箭头
ax.annotate(s='x' ,xy=(2*math.pi,0) ,xytext=(2*math.pi,0.1)) #标注x轴
ax.annotate(s='y' ,xy=(0,1.0) ,xytext=(-0.5,1.0)) #标注y轴

(PS If subplots pyplot method of use, will not be successful; so honestly axisartist method to use! )

 

IV. We draw the function image

Obviously we have to use our plot function, here, by the way our three uses plot function

  1.  X and Y given all points , drawing a vector graph .
  2. Directly given on a function of X and X (X + EG. 1) , to draw the contents of the expression.
  3. Two incoming list, each list, there are two elements x or y are the initial and terminal positions ; according to the two coordinates to draw a straight line .

We use the first method, the drawn back to draw linestyle sin and cos it is "-" We use the third straight line method.

We can use Python's sequence unpacking be simple assignment .

# 准备数据,利用sequence unpacking
X  = np.linspace(-np.pi, np.pi, 100, endpoint=True) # 这个endpoint非常细节
C, S = np.cos(X), np.sin(X)

# 绘制图像
plt.plot(X, C, color='b', label="Cos Function")
plt.plot(X, S, color='r', label="Sin Function")
# 绘制linestyle="--"的两条直线
t = np.pi * 2 / 3;
plt.plot([t, t], [0, np.sin(t)], color='r', linestyle="--")
plt.plot([t, t], [0, np.cos(t)], color='b', linestyle="--")

 

V. modify the scale on the coordinate system

Here we have to do two things:

  1.  Determining the range of the whole coordinate axis can be represented . --Plt.xlim, plt.ylim
  2.  Determine the axis on which numbers are to be expressed particular , and then have marked out . --Plt.xticks, plt.yticks
# 修改图中坐标系表示的最大和最小值
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(-1.1, 1.1)

# 修改坐标轴上的标签
x_numbers = [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]
x_labels = [r"$-\pi$", r"$-\pi$", r"$0$", r"$\pi/2$", r"$\pi$"] # python中使用LaTex得加上$$, 最好向他这样转义
plt.xticks(x_numbers, x_labels)
y_numbers = [-1, 1]
y_labels = ["-1", "1"]
plt.yticks(y_numbers, y_labels)

 

VI. Draw a comment

Draw two scatter we will not mention, direct talk here how to draw comments:

From matplotlib we found:

  1. xy is the figure you want to comment points.
  2. xytext a comment locations.
  3. xycoords and textcoords seems to be a variety of offset? Anyway, this just fine with default values
  4. arrorprops is an arrow.
# 补充记号
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
             xy=(t, np.sin(t)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

 

VII. Draw Legend

Legend also draw a plot.legend trouble, but I will not say so.

I would like to mention is: if you plot before given a label when there is no need to display a given label ,

As long as keyword arguments passed, our borders can be eliminated .

# 设置图例
# 如果上面制定了label, 那这里就不用传入列表!
plt.legend(frameon=False)

 

VIII. Source

https://labfile.oss.aliyuncs.com/courses/892/sin_cos_functions.py

发布了137 篇原创文章 · 获赞 19 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_43338695/article/details/102994436