如何在共享X、Y轴的Matplotlib双图中合并X、Y轴刻度
I see the issue here—when you call ax.set_xticks() twice in a row, the second call completely overwrites the first one, which is why only the ticks from your second dataset are showing up. The same goes for the Y-axis ticks. To fix this, you need to combine the tick values from both datasets first, then set them on the axis once.
Fixed Code
import matplotlib.pyplot as plt import matplotlib.dates as md from datetime import datetime # Dataset 1 v1 = datetime.fromisoformat("2022-10-15T23:45:51.159618277Z") v2 = datetime.fromisoformat("2022-10-16T23:49:51.159618277Z") v3 = datetime.fromisoformat("2022-10-17T22:25:46.638699435Z") t_time_values1 = [v1, v2, v3] datenums1 = md.date2num(t_time_values1) y1 = [30, 15, 45] # Dataset 2 v4 = datetime.fromisoformat("2022-10-15T05:45:51.159618277Z") v5 = datetime.fromisoformat("2022-10-16T05:49:51.159618277Z") v6 = datetime.fromisoformat("2022-10-17T02:25:46.638699435Z") t_time_values2 = [v4, v5, v6] datenums2 = md.date2num(t_time_values2) y2 = [78, 25, 55] # Plot lines ax = plt.gca() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S.%f') ax.xaxis.set_major_formatter(xfmt) plt.plot(datenums1, y1, label="line 1") plt.plot(datenums2, y2, label="line 2") # Combine and sort X-axis ticks (dates are numerical, so sorting works) combined_xticks = sorted(datenums1 + datenums2) ax.set_xticks(combined_xticks) # Combine and sort Y-axis ticks combined_yticks = sorted(y1 + y2) ax.set_yticks(combined_yticks) # Rotate X-tick labels for readability (optional but recommended) plt.xticks(rotation=45) plt.legend() plt.tight_layout() # Adjust layout to prevent label cutoff plt.show()
Key Changes Explained:
- Combining Tick Values: Instead of setting ticks twice, we merge the tick lists from both datasets (
datenums1 + datenums2for X,y1 + y2for Y) and sort them. This ensures all unique tick positions are included and ordered correctly. - Avoid Overwriting: By calling
ax.set_xticks()andax.set_yticks()only once with the combined lists, we preserve all ticks from both plots. - Readability Improvements: Added
plt.xticks(rotation=45)andplt.tight_layout()to prevent long date labels from getting cut off.
Why Your Original Code Didn't Work:
Matplotlib's set_xticks() replaces the existing tick array each time you call it. So when you ran ax.set_xticks(datenums1) followed by ax.set_xticks(datenums2), the first set of ticks was discarded entirely—only the second set remained. Merging the lists first fixes this by including all desired tick positions in one go.
内容的提问来源于stack exchange,提问作者User1751
相关产品推荐
相关产品推荐

