Повернуть ось Matplotlib X на двухосном графике - PullRequest
0 голосов
/ 27 января 2020

Я пытаюсь повернуть метки оси 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()

1 Ответ

0 голосов
/ 28 января 2020

за комментарий @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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...