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^2 y1=x2
y 2 = x 3 y_2=x^3 y2=x3

With the aid NumPy we can create a vector with entries for x x x and calculate y 1 y_1 y1 and y 2 y_2 y2:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值