Pandas bar plot всегда создает пустой участок - PullRequest
0 голосов
/ 07 июня 2018

Я хочу построить два столбчатых графика на одной фигуре, но я всегда терплю неудачу.

Ниже мой код:

def plot_data_group2(factor,xlabel): #xlabel: 这里是为了x轴坐标设置的
    survived_count=survived_passenger.groupby([factor])['PassengerId'].count()    
    fig_1 = plt.figure() #指定figure的宽和高,单位为英寸
    fig_1=plt.subplot(121)
    survived_count.plot(kind='bar')
    fig_1.set_title('Survived rate group by ' + factor)
    fig_1.set_xlabel(factor)
    fig_1.set_ylabel("count of the survived")
    plt.xticks(rotation=0) #旋转x轴的标签至水平(默认是和x轴垂直的)    
    fig_2=plt.subplot(122)
    survived_count_group = titanic_data.groupby([factor, 'Survived'])['PassengerId'].count().unstack()
    survived_rate = survived_count_group.apply(lambda x: (x / x.sum() * 100),axis=1)
    survived_rate.plot(kind='bar')
    fig_2.set_title('Survived rate group by ' + factor)
    fig_2.set_xlabel(factor)
    fig_2.set_ylabel("ration of " + factor + " in the survived")
    plt.xticks(rotation=0)    
    #plt.show()
plot_data_group2('Age_group',['under 18','young','not old','old'])

Вывод следующий:

1

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

Я не знаю точно, почему pandas DataFrame.plot не работает точно так же, как при построении данных с использованием pyplot.plot.

Однако вы можете явно передавать оси в DataFrame.plot с аргументами ключевых слов.,Посмотрите, имеет ли этот пример какой-либо смысл.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# random test data
x = np.linspace(0, 1, 20)
y = x ** 2
# data in a pandas frame with 2 columns
df = pd.DataFrame([x, y]).T

fig, ax = plt.subplots(1, 2) # (n rows, n cols)
df.plot(0, 1, ax=ax[0])
df.plot(0, 1, ax=ax[1])
plt.show()
0 голосов
/ 07 июня 2018

Изменить survived_rate.plot(kind='bar') на survived_rate.plot(kind='bar', ax=fig_2).

enter image description here

...