简体   繁体   中英

How to plot a scatter plot and a line plot as a subplot in one plot?

I have the following codes:

For scatter plot:

plt.scatter(x_1.values[y_ocsvm1 == 1, 2], scaled_array[y_ocsvm1 == 1, 0], c = 'red', label = 'cluster1')
plt.scatter(x_1.values[y_ocsvm1 == -1, 2], scaled_array[y_ocsvm1 == -1, 0], c = 'blue', label = 'cluster2')
plt.ticklabel_format(useOffset=False)
plt.yticks(np.arange(min(scaled_array[:,[0]]), max(scaled_array[:,[0]]), 0.05))
plt.legend()
plt.show()

This gives me: 在此处输入图片说明

For line plot:

plt.plot(x, y)

This gives me:

在此处输入图片说明

I would like to plot both these two as subplots in the same plot (Vertically stacked plots).

I would like to know how can this be done

Thanks

Edit:

I tried doing:

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
ax1.plot(x, y)
ax2.plot(plt.scatter(x_1.values[y_ocsvm1 == 1, 2], scaled_array[y_ocsvm1 == 1, 0], c = 'red', label = 'cluster1')
, plt.scatter(x_1.values[y_ocsvm1 == -1, 2], scaled_array[y_ocsvm1 == -1, 0], c = 'blue', label = 'cluster2'))

And it gives me the desired plot as follows: 在此处输入图片说明

But it also shows the following error:

TypeError: float() argument must be a string or a number, not 'PathCollection'

Try the following

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)

ax1.plot(x, y)

ax2.scatter(x_1.values[y_ocsvm1 == 1, 2], scaled_array[y_ocsvm1 == 1, 0], 
            color='red', label='cluster1')
ax2.scatter(x_1.values[y_ocsvm1 == -1, 2], scaled_array[y_ocsvm1 == -1, 0], 
            color='blue', label='cluster2')

plt.legend() # To show the legend

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