Matplotlib绘制简单函数图像

In a good pythonic style, matplotlib is an object oriented plotting library that can generate a variety of visualisations: From simple plots, histograms, bar charts, scatterplots and more with a few lines of code. If you are familiar with Matlab or Octave, you will find pylab very easy to use. Let us start by importing the modules.

import numpy as np
import matplotlib.pyplot as plt
from pylab import*

Let us create a simple figure to plot the following functions:

y 1 = x 2 y_1=x^2y1=x2
y 2 = x 3 y_2=x^3y2=x3

With the aid NumPy we can create a vector with entries for x xx and calculate y 1 y_1y1 and y 2 y_2y2:

x = np.linspace(-5, 5, 200)
y1 = x**2
y2 = x**3

We can create a plot using the plot command as follows:

fig, ax = plt.subplots()
ax.plot(x, y1, 'r', label=r"$y_1=x^2$", linewidth=2)
ax.plot(x, y2, 'k--', label=r"$y_2=x^3$", linewidth=2)
ax.legend(loc=2)
ax.set_xlabel(r'$x$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('My Figure')
plt.show()

请添加图片描述
Remember that matplotlib is an object oriented library and thus we are using objects to create our plots. The commands above are very similar to those used in Matlab and Octave and should you need to take a closer look at the syntax you can consult other resource. The result of the commands above can be seen in above. Finally, it is possible to save the plot to a file with a single command. In this case we can create a PNG file with the following line of code:

fig.savefig('firstplot.png')

reference

Data Science and Analytics with Pyhton by Jesus Rogel-Salazar


版权声明:本文为weixin_44507034原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。