Установка предела x на объектах вторых осей также изменяет положения x-tick по умолчанию для этих осей.Вы можете узнать, как печатать ax2.get_xticks()
до и после вызова ax2.set_xlim(ax.get_xlim())
.
Вам необходимо явно (пере) установить позиции x-tick после изменения предела x с помощью ax2.set_xticks()
,и установите их для ax
.
Ниже приведен полный пример:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'message_count': [557, 119, 108, 14, 9],
'coin': ['MEDX', 'CNX', 'IOST', 'AUTO', 'PPT'],
'create_date': ['2018-08-03 03:05:00',
'2017-08-10 14:33:45',
'2018-07-20 18:32:45',
'2017-12-08 15:09:42',
'2017-07-24 14:11:22']})
df['create_date'] = pd.to_datetime(df['create_date'])
print(df)
fig, ax = plt.subplots(figsize=(15,5))
index = df.coin
rects1 = ax.bar(index, df['message_count'])
ax.set_xlabel('Group')
ax.set_ylabel('message count')
ax.set_title('')
ax.legend()
ax2 = ax.twiny()
ax2.set_xticklabels(df.create_date)
ax2.xaxis.set_ticks_position('bottom') # set the position of the second x-axis to bottom
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 38))
ax2.set_xlabel('Create Date')
ax2.set_xlim(ax.get_xlim())
ax2.set_xticks(ax.get_xticks())
plt.tight_layout()
plt.savefig('twinplot.png')
, который дает
