matplotlib 使用twinx打印旋转x轴刻度

2ic8powd  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(126)

我尝试将x轴标签旋转90度,这通常适用于下面的category_amts()函数的最后一行。然而,由于这是一个双轴视觉,该方法不起作用。
如何在这样的双轴图表上旋转轴标签?

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. df = pd.DataFrame({'place': ['restaurant', 'gas station', 'movie theater', 'grocery store'],
  5. 'amount': [50, 65, 32, 70]})
  6. df = df.sort_values('amount', ascending = False)
  7. df['cumpercentage'] = df['amount'].cumsum() / df['amount'].sum()
  8. x_pos = np.arange(len(df.index))
  9. def category_amts():
  10. plt.rcParams['figure.figsize'] = (18,8)
  11. plt.rcParams["font.size"] = 12
  12. fig, ax = plt.subplots()
  13. ax.bar(x_pos, df['amount'], color = 'C0')
  14. ax2 = ax.twinx()
  15. ax2.plot(x_pos, df['cumpercentage'], color = 'C3', marker = 'D', ms = 7)
  16. ax.tick_params(axis = 'y', colors = 'C0')
  17. ax2.tick_params(axis = 'y', colors = 'C3')
  18. ax.xaxis.label.set_color('black')
  19. ax2.xaxis.label.set_color('black')
  20. ax.grid(False)
  21. ax2.grid(False)
  22. plt.title('Transactions by Merchant Category')
  23. ax.set_xlabel('Merchant Category')
  24. ax.set_ylabel('Transaction Count')
  25. ax2.set_ylabel('Cummulative % of Transaction Amounts', rotation = 270, labelpad = 15)
  26. plt.xticks(x_pos, df['place'], rotation = 90)
  27. category_amts()
lokaqttq

lokaqttq1#

根据@BigBen的评论,我需要移动我调用plt.xticks的位置。参见以下可重现溶液:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. df = pd.DataFrame({'place': ['restaurant', 'gas station', 'movie theater', 'grocery store'],
  5. 'amount': [50, 65, 32, 70]})
  6. df = df.sort_values('amount', ascending = False)
  7. df['cumpercentage'] = df['amount'].cumsum() / df['amount'].sum()
  8. x_pos = np.arange(len(df.index))
  9. def category_amts():
  10. plt.rcParams['figure.figsize'] = (18,8)
  11. plt.rcParams["font.size"] = 12
  12. fig, ax = plt.subplots()
  13. plt.xticks(x_pos, df['place'], rotation=90)
  14. ax.bar(x_pos, df['amount'], color = 'C0')
  15. ax2 = ax.twinx()
  16. ax2.plot(x_pos, df['cumpercentage'], color = 'C3', marker = 'D', ms = 7)
  17. ax.tick_params(axis = 'y', colors = 'C0')
  18. ax2.tick_params(axis = 'y', colors = 'C3')
  19. ax.xaxis.label.set_color('black')
  20. ax2.xaxis.label.set_color('black')
  21. ax.grid(False)
  22. ax2.grid(False)
  23. plt.title('Transactions by Merchant Category')
  24. ax.set_xlabel('Merchant Category')
  25. ax.set_ylabel('Transaction Count')
  26. ax2.set_ylabel('Cummulative % of Transaction Amounts', rotation = 270, labelpad = 15)
  27. category_amts()
展开查看全部

相关问题