Public id: Python Programming time

So what I’m going to do today is draw sines and cosines, and start with the default Settings, and I’m going to tweak it a little bit, and make it look nice, like we’ve seen in junior high and high school. Learn how to make adjustments to some elements of the diagram.

01. Simple drawing

Matplotlib has a set of default Settings that allow you to customize various properties. You can control almost every default attribute in Matplotlib: image size, points per inch, line width, color and style, axes, axes and grid attributes, text and font attributes, and so on.

While the default Settings for Matplotlib are pretty good in most cases, you may want to change some properties in particular cases.

from pylab import *

x = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(x), np.sin(x)

plot(x,C)
plot(x,S)

show()
Copy the code

show image

02. Set basic elements

The basic elements here are as follows:

  1. The color, thickness, and shape of the line
  2. Scale and label
  3. There are illustrations

The code is pretty simple, and I basically covered it in my first lecture.

import numpy as np
from matplotlib import pyplot as plt

plt.figure(figsize=(10.6), dpi=80)
x = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(x), np.sin(x)

Set the color, thickness, and type of the line
plt.plot(x, C, color="blue", linewidth=2.5, linestyle="-", label=r'$sin(x)$')
plt.plot(x, S, color="red",  linewidth=2.5, linestyle="-", label=r'$cos(x)$')

# If you feel the line is too close to the boundary, you can increase the distance
plt.xlim(x.min()*1.2, x.max()*1.2)
plt.ylim(C.min()*1.2, C.max()*1.2)

# The current scale is not clear, need to reset and add more intuitive labels
plt.xticks([-np.pi, -np.pi/2.0, np.pi/2, np.pi],
          [r'$-\pi$'.r'$-\pi/2$'.r'$0$'.r'$+\pi/2$'.r'$+\pi$'])
plt.yticks([- 1.0.1],
          [r'$-1$'.r'$0$'.r'$1$'])

# add legend
plt.legend()

plt.show()
Copy the code

show image

03. Move the axis

Remember the trigonometric graph that we learned in junior high school, it’s not like that, it’s supposed to have four quadrants. And here’s a boxy chart.

So what we’re going to do is we’re going to move the axis around and make it look something we’re familiar with.

We only need two axes (x and y), so we need to hide the top and right axes (color set to None).

Get current Axis # plt.gca(
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Since we are moving the left and bottom axes, we can do without setting these two
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

Move the data type to the specified value
ax.spines['bottom'].set_position(('data'.0))
ax.spines['left'].set_position(('data'.0))
Copy the code

What about data in set_position()? I checked the official website. Explain the following

And then it turns out that this is equivalent to something that can be set up in a much cleaner way.

ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')
Copy the code

show image

04. Add comments

Now that the graphics are in place, let’s annotate some of the points we’re interested in using the annotate command.

We chose 2 PI over 3 as the sines and cosines we wanted to annotate. We will make a mark and a vertical dotted line on the curve. Then, use the annotate command to display an arrow and some text.

t = 2*np.pi/3

Plot a vertical line downward and a point using PLt. scatter.
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')

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"))

# Draw a vertical line upwards using PLt. plot and a point using PLt. scatter.
plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')

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"))
Copy the code

Now, you might not be familiar with the use of the plt.annotate function. Let me explain it here.

The first parameter is the comment content; The second argument, xy, is what point to comment on; The third argument, xycoords, specifies the type. Data means to locate based on a number; The fourth argument, xytext, is the position of the comment, combined with the fifth argument, which determines the position of the comment based on the offset; The fifth argument, TextCoords, is offset points, which is the relative position; The sixth argument, fontsize, comment size; The seventh parameter, arrowprops, sets some of the types of arrows.

show image

05. Complete code

The above is to explain the snippet code, here is the full code

import numpy as np
from matplotlib import pyplot as plt

plt.figure(figsize=(10.6), dpi=80)
x = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(x), np.sin(x)

Set the color, thickness, and type of the line
plt.plot(x, C, color="blue", linewidth=2.5, linestyle="-", label=r'$sin(x)$')
plt.plot(x, S, color="red",  linewidth=2.5, linestyle="-", label=r'$cos(x)$')

# If you feel the line is too close to the boundary, you can increase the distance
plt.xlim(x.min()*1.2, x.max()*1.2)
plt.ylim(C.min()*1.2, C.max()*1.2)

# The current scale is not clear, need to reset and add more intuitive labels
plt.xticks([-np.pi, -np.pi/2.0, np.pi/2, np.pi],
          [r'$-\pi$'.r'$-\pi/2$'.r'$0$'.r'$+\pi/2$'.r'$+\pi$'])
plt.yticks([- 1.1],
          [r'$-1$'.r'$1$'])

# add legend
plt.legend(loc='upper left')

Get current Axis # plt.gca(
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Since we are moving the left and bottom axes, we can do without setting these two
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

Move the data type to the specified value
# ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_position(('data'.0))
ax.spines['left'].set_position(('data'.0))

t = 2*np.pi/3

Plot a vertical line downward and a point using PLt. scatter.
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')

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"))

# Draw a vertical line upwards using PLt. plot and a point using PLt. scatter.
plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')

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"))

plt.show()
Copy the code