1

Trying to get rid of on x axis overlapping issue. I couldn't change angle of the values

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()
1
  • fig.autofmt_xdate()? Commented Jan 24, 2024 at 17:30

1 Answer 1

0

You could use matplotlib.pyplot.setp() with proper rotation and horizontal alignment arguments. An example with some randomly generated data:

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()

The result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.