Home > Blockchain >  Matplotlib scatter plot dual y-axis
Matplotlib scatter plot dual y-axis

Time:05-10

I try to figure out how to create scatter plot in matplotlib with two different y-axis values. Now i have one and need to add second with index column values on y.

points1 = plt.scatter(r3_load["TimeUTC"], r3_load["r3_load_MW"],
                     c=r3_load["r3_load_MW"], s=50, cmap="rainbow", alpha=1) #set style options
plt.rcParams['figure.figsize'] = [20,10]
#plt.colorbar(points)

plt.title("timeUTC vs Load")
#plt.xlim(0, 400)
#plt.ylim(0, 300)
plt.xlabel('timeUTC')
plt.ylabel('Load_MW')
cbar = plt.colorbar(points1)
cbar.set_label('Load')

enter image description here

Result i expect is like this: enter image description here

So second scatter set should be for TimeUTC vs index. Colors are not the subject;) also in excel y-axes are different sites, but doesnt matter.

Appriciate your help! Thanks, Paulina

CodePudding user response:

Continuing after the suggestions in the comments.

There are two ways of using matplotlib.

  • Via the matplotlib.pyplot interface, like you were doing in your original code snippet with .plt
  • The object-oriented way. This is the suggested way to use matplotlib, especially when you need more customisation like in your case. In your code, ax1 is an Axes instance.

From an Axes instance, you can plot your data using the Axes.plot and Axes.scatter methods, very similar to what you did through the pyplot interface. This means, you can write a Axes.scatter call instead of .plot and use the same parameters as in your original code:

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.scatter(r3_load["TimeUTC"], r3_load["r3_load_MW"],
                     c=r3_load["r3_load_MW"], s=50, cmap="rainbow", alpha=1)
ax2.plot(r3_dda249["TimeUTC"], r3_dda249.index, c='b', linestyle='-')

ax1.set_xlabel('TimeUTC')
ax1.set_ylabel('r3_load_MW', color='g')
ax2.set_ylabel('index', color='b')

plt.show()
  • Related