【问题标题】:X-ticks in a subplots line graph are different python plot子图线图中的 X-ticks 是不同的 python 图
【发布时间】:2020-10-25 03:00:35
【问题描述】:

除了图表类型外,我对多个图表使用相同的代码。第一个子图的 X-ticks 没问题,但正如您在下图中看到的,其他两个子图的 x-ticks 缩小了,即使图形线显示了确切的位置。可能有什么解决办法?

# Library Loading
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import pandas as pd


df_1 = pd.DataFrame({
    "A":[22.34,25.10,37.57,44.96,53.09],
    "B":[18.42,31.09,33.66,41.73,51.31],})

df_2 = pd.DataFrame({
    "A":[44.85,44.44,44.43,44.06,45.01],  
    "B":[48.46,44.59,43.51,44.42,45.38],})

df_3= pd.DataFrame({
    "A":[2.88,6.58,8.35,14.77,20.21],
    "B":[1.76,5.25,9.18,12.47,19.22],})


plt.figure(num=1)
fig, (ax,ax1,ax2) = plt.subplots(3,1,figsize=(8,12))
# twin_x = ax.twinx() # Create a pseudo axes based off of the original
fig.subplots_adjust(hspace=0.5)

#************** Graph in First row ************************
# Put the bar plot on the "primary y" via ax=ax
df_1[['A','B']]. \
plot(kind='bar',color=['purple','steelblue'], ax=ax, zorder=1,legend=True, width=.40)
ax.grid(True, zorder=0)
ax.set_axisbelow(True)
ax.set_xticklabels(('10', '20','30', '40', '50'),Rotation=360)

# X and Y axis label
ax.set_xlabel('Number of P',fontsize=12)
ax.set_ylabel('(%)',fontsize=12)

#************** Graph in Second row ************************
# Put the bar plot on the "primary y" via ax=ax
df_2[['A','B']]. \
plot(kind='line',color=['purple','steelblue'], ax=ax1, zorder=2,legend=True,marker='*')
ax1.grid(True, zorder=2)
ax1.set_axisbelow(True)
ax1.set_xticklabels(('10', '20','30', '40', '50'),Rotation=360)

# X and Y axis label
ax1.set_xlabel('Number of P',fontsize=12)
ax1.set_ylabel(' (%)',fontsize=12)

#************** Graph in Third row ************************
# Put the bar plot on the "primary y" via ax=ax
df_3[['A','B']]. \
plot(kind='line',color=['purple','steelblue'], ax=ax2, zorder=3,legend=True, marker='o')


ax2.grid(True, zorder=3)
ax2.set_axisbelow(True)
ax2.set_xticklabels(('10', '20','30', '40', '50'),Rotation=360)

# X and Y axis label
ax2.set_xlabel('Number of P',fontsize=12)
ax2.set_ylabel('Time (Seconds)',fontsize=12)

plt.show()

以下是代码中的图像供您参考。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    那是因为后两个图是线图,x 轴是数字,matplotlib 会自动缩放xticks。在这种情况下,后两者的xticks 在第一个图中是[0,0.5,1,...]0,1,2,3,4

    您可以做的一件简单的事情是将sharex=True 传递给subplots

    fig, (ax,ax1,ax2) = plt.subplots(3,1,figsize=(8,12), sharex=True)
    

    你会得到:

    或者您可以手动强制线图的 xticks:

    # other code
    ax2.set_xticks(df_2.index)
    ax2.set_xticklabels(('10', '20','30', '40', '50'),Rotation=360)
    
    # same for `ax3`
    

    你会得到:

    【讨论】:

    • 感谢 Quang 的解释。你的两个解决方案都很好,我需要第二个。
    • 再次感谢,但是您知道如何使折线图中的线平滑吗?提前致谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2015-03-30
    相关资源
    最近更新 更多