我想在一个图中绘制两个条形图,但我总是失败。
以下是我的代码:
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'])
输出如下:
答案 0 :(得分:3)
答案 1 :(得分:0)
我不确切地知道为什么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()