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

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

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

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

lokaqttq1#

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

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

相关问题