Reputation: 1223
I'm trying to rotate the x-axis labels by 90 degrees, which typically works with the last line of the category_amts()
function below. However, because this is a dual-axis visual, the approach is not working.
How do you rotate axis labels on a dual-axis chart like this?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'place': ['restaurant', 'gas station', 'movie theater', 'grocery store'],
'amount': [50, 65, 32, 70]})
df = df.sort_values('amount', ascending = False)
df['cumpercentage'] = df['amount'].cumsum() / df['amount'].sum()
x_pos = np.arange(len(df.index))
def category_amts():
plt.rcParams['figure.figsize'] = (18,8)
plt.rcParams["font.size"] = 12
fig, ax = plt.subplots()
ax.bar(x_pos, df['amount'], color = 'C0')
ax2 = ax.twinx()
ax2.plot(x_pos, df['cumpercentage'], color = 'C3', marker = 'D', ms = 7)
ax.tick_params(axis = 'y', colors = 'C0')
ax2.tick_params(axis = 'y', colors = 'C3')
ax.xaxis.label.set_color('black')
ax2.xaxis.label.set_color('black')
ax.grid(False)
ax2.grid(False)
plt.title('Transactions by Merchant Category')
ax.set_xlabel('Merchant Category')
ax.set_ylabel('Transaction Count')
ax2.set_ylabel('Cummulative % of Transaction Amounts', rotation = 270, labelpad = 15)
plt.xticks(x_pos, df['place'], rotation = 90)
category_amts()
Upvotes: 0
Views: 1474
Reputation: 1223
per @BigBen comment, I needed to move the where I was calling plt.xticks
. See reproducible solutions below:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'place': ['restaurant', 'gas station', 'movie theater', 'grocery store'],
'amount': [50, 65, 32, 70]})
df = df.sort_values('amount', ascending = False)
df['cumpercentage'] = df['amount'].cumsum() / df['amount'].sum()
x_pos = np.arange(len(df.index))
def category_amts():
plt.rcParams['figure.figsize'] = (18,8)
plt.rcParams["font.size"] = 12
fig, ax = plt.subplots()
plt.xticks(x_pos, df['place'], rotation=90)
ax.bar(x_pos, df['amount'], color = 'C0')
ax2 = ax.twinx()
ax2.plot(x_pos, df['cumpercentage'], color = 'C3', marker = 'D', ms = 7)
ax.tick_params(axis = 'y', colors = 'C0')
ax2.tick_params(axis = 'y', colors = 'C3')
ax.xaxis.label.set_color('black')
ax2.xaxis.label.set_color('black')
ax.grid(False)
ax2.grid(False)
plt.title('Transactions by Merchant Category')
ax.set_xlabel('Merchant Category')
ax.set_ylabel('Transaction Count')
ax2.set_ylabel('Cummulative % of Transaction Amounts', rotation = 270, labelpad = 15)
category_amts()
Upvotes: 1