简体   繁体   中英

Plot function and Scatter on the same graph

I am trying to plot the function y = x**2 and a scatter on the same graph. I have found lots of people talking about having two functions or two scatters on the same graph but I was wondering if anyone knows how to plot a function and a scatter on the same graph. I am using Python with the matplotlib library.

You can combine multiple objects in one figure:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, num=10)
y = x**2
obj1 = plt.plot(x, y)
obj2 = plt.scatter(x, y)
plt.show()

在此处输入图片说明

Sample run:

>>> obj1 #list of all lines
[<matplotlib.lines.Line2D at 0x228c2de91f0>]
>>> obj2 #collections
<matplotlib.collections.PathCollection at 0x228c5459a00>

Just use the respective functions of the matplotlib module:

from matplolib import pyplot as plt
t=np.linspace(x_low,x_high,numpoints)
plt.plot(t,t**2)
plt.scatter(x_data,y_data)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM