简体   繁体   中英

How to add xticks to plot with secondary y-axis

I have the following MWE, which plots two columns of a pandas dataframe in one single plot where each column has its own y-axis:

df = pd.DataFrame({'t': [2000, 2002, 2004, 2006],
                   'a': [2, 4, 6, 8],
                   'b': [100, 200, 300, 400]})

fig = plt.figure(figsize=(10, 10))
plt.xticks(np.arange(2000, 2020, 2))

ax1 = df['b'].plot(label="b")
ax1.set_ylabel("b")
ax1.set_ylim(0, 500)

ax2 = df['a'].plot(secondary_y=True, label="a")
ax2.set_ylabel("a")
ax2.set_ylim(0, 5)

handles, labels = [], []
for ax in fig.axes:
    for h, l in zip(*ax.get_legend_handles_labels()):
        handles.append(h)
        labels.append(l)
plt.legend(handles, labels)

However, the x-ticks are missing although I have tried to add them with this line of code: plt.xticks(np.arange(2000, 2020, 2)) .

What command do I need to add them besides what I already have?

在此处输入图片说明

You need to specify the limit of x axis. The following solution can help.

df = pd.DataFrame({'t': [2000, 2002, 2004, 2006],
                   'a': [2, 4, 6, 8],
                   'b': [100, 200, 300, 400]})

fig = plt.figure(figsize=(10, 10))
plt.xticks(np.arange(2000, 2020, 2))

ax1 = df['b'].plot(label="b")
ax1.set_ylabel("b")
ax1.set_ylim(0, 500)

ax2 = df['a'].plot(secondary_y=True, label="a")
ax2.set_ylabel("a")
ax2.set_ylim(0, 5)

ax3 = df['t'].plot(label="t")
ax3.set_xlabel("t")
ax3.set_xlim(2000,2020)

handles, labels = [], []
for ax in fig.axes:
    for h, l in zip(*ax.get_legend_handles_labels()):
        handles.append(h)
        labels.append(l)
plt.legend(handles, labels)

plt.xticks(np.arange(2000, 2020, 2)) sets the ticks to be at positions 2000, 2002, etc. However your plot ranges from 0 to 4, because that is the index of the dataframe.

Either set the index to the values of the "t" column,

df.set_index("t", inplace=True)
ax1 = df['b'].plot(label="b")

or plot the columns directly

ax1 = df.plot(x="t", y="b", label="b")

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