Matplotlib X 轴名称重叠?

问题描述 投票:0回答:1

尝试摆脱 x 轴重叠问题。我无法改变数值的角度

enter image description here

# Create a figure with sharing x-axis
fig, ax1 = plt.subplots(figsize=(10, 6))

# weekly order count on the left y-axis
ax1.bar(weekly_order_count.index.astype(str), weekly_order_count['id_order'], label='Weekly Order Count', color='skyblue')
ax1.set_ylabel('Order Count', color='skyblue')
ax1.tick_params('y', colors='skyblue')

# second y-axis for the discount rate on the right side
ax2 = ax1.twinx()
ax2.plot(weekly_discount_rate.index.astype(str), weekly_discount_rate['disc_pct'], label='Weekly Discount Rate', color='orange', marker='o', linestyle='--')
ax2.set_ylabel('Discount Rate (%)', color='orange')
ax2.tick_params('y', colors='orange')

# titles and labels
plt.title('Comparison of Weekly Order Count and Weekly Discount Rate')
plt.xlabel('Week')
plt.xticks(rotation=45)
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper left')
plt.show()
python matplotlib rotation overlapping xticks
1个回答
0
投票

您可以使用 matplotlib.pyplot.setp() 以及适当的旋转和水平对齐参数。一些随机生成的数据的示例:

import matplotlib.pyplot as plt
import numpy as np

# Create a figure with sharing x-axis
fig, ax1 = plt.subplots(figsize=(10, 6))

weekly_order_count = np.random.randint(0, 3600, 61)
weekly_discount_rate = np.random.uniform(0.13, 0.24, 61)

# weekly order count on the left y-axis
ax1.bar(['Week {}'.format(str(i + 1)) for i in range(len(weekly_order_count))], weekly_order_count, label='Weekly Order Count', color='skyblue')
ax1.set_ylabel('Order Count', color='skyblue')
ax1.tick_params('y', colors='skyblue')

# second y-axis for the discount rate on the right side
ax2 = ax1.twinx()
ax2.plot(['Week {}'.format(str(i + 1)) for i in range(len(weekly_discount_rate))], weekly_discount_rate, label='Weekly Discount Rate', color='orange', marker='o', linestyle='--')
ax2.set_ylabel('Discount Rate (%)', color='orange')
ax2.tick_params('y', colors='orange')

# titles and labels
plt.title('Comparison of Weekly Order Count and Weekly Discount Rate')
plt.xlabel('Week')
plt.setp(ax1.get_xticklabels(), rotation=45 , ha='right')
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper left')
plt.show()

结果:

© www.soinside.com 2019 - 2024. All rights reserved.