【发布时间】:2013-10-27 13:16:17
【问题描述】:
Python 中的普通 matplotlib boxplot 命令返回一个字典,其中包含框、中值、胡须、传单和大写的键。这让造型变得非常容易。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Create a dataframe and subset it for a boxplot
df1 = pd.DataFrame(rand(10), columns=['Col1'] )
df1['X'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])
boxes= [df1[df1['X'] == 'A'].Col1, df1[df1['X'] == 'B'].Col1]
# Call the standard matplotlib boxplot function,
# which returns a dictionary including the parts of the graph
mbp = plt.boxplot(boxes)
print(type(mbp))
# This dictionary output makes styling the boxplot easy
plt.setp(mbp['boxes'], color='blue')
plt.setp(mbp['medians'], color='red')
plt.setp(mbp['whiskers'], color='blue')
plt.setp(mbp['fliers'], color='blue')
Pandas 库为其分组(分层索引)数据帧提供了“优化”箱线图功能。然而,它不是为每个组返回几个字典,而是返回一个 matplotlib.axes.AxesSubplot 对象。这使得造型非常困难。
# Pandas has a built-in boxplot function that returns
# a matplotlib.axes.AxesSubplot object
pbp = df1.boxplot(by='X')
print(type(pbp))
# Similar attempts at styling obviously return TypeErrors
plt.setp(pbp['boxes'], color='blue')
plt.setp(pbp['medians'], color='red')
plt.setp(pbp['whiskers'], color='blue')
plt.setp(pbp['fliers'], color='blue')
pandas df.boxplot(by='X') 函数生成的这个 AxisSubplot 对象是否可访问?
【问题讨论】:
-
你能给我们看一些示例代码(带有假数据吗?)
-
我已编辑问题以包含示例数据和代码,并更清楚地展示我的问题。
标签: python matplotlib pandas