简体   繁体   English

matplotlib/Pandas 中的水平箱线图

[英]Horizontal box plots in matplotlib/Pandas

Bar plots:条形图:

matplotlib offers the function bar and barh to do vertical and horizontal bar plots. matplotlib提供 function barbarh来绘制垂直水平条形图。

Box plots:箱形图:

matplotlib also offers the function boxplot to do vertical box plots. matplotlib还提供 function boxplot来绘制垂直箱线图。

And Pandas offers its own function for vertical box plots. Pandas垂直箱形图提供了自己的 function

But is there any way in matplotlib or Pandas to get a horizontal box plot?但是在 matplotlib 或 Pandas 有什么办法可以得到一个水平框 plot?

matplotlib's boxplot(..., vert=False) makes horizontal box plots. matplotlib 的boxplot(..., vert=False)制作水平箱线图。 The keyword parameter vert=False can also be passed to DataFrame.boxplot :关键字参数vert=False也可以传递给DataFrame.boxplot

import matplotlib.pyplot as plt
import pandas as pd
x = [[1.2, 2.3, 3.0, 4.5],
     [1.1, 2.2, 2.9, 5.0]]
df = pd.DataFrame(x, index=['Age of pregnant women', 'Age of pregnant men'])

df.T.boxplot(vert=False)
plt.subplots_adjust(left=0.25)
plt.show()

在此处输入图片说明

I see from the comment (below) that the motivation for making a horizontal box plot is that the labels are rather long.我从评论(下面)中看到,制作水平箱线图的动机是标签相当长。 Another option in that case might be to rotate the xticklabels:在这种情况下,另一种选择可能是旋转 xticklabels:

import matplotlib.pyplot as plt
import pandas as pd
x = [[1.2, 2.3, 3.0, 4.5],
     [1.1, 2.2, 2.9, 5.0]]
df = pd.DataFrame(x, index=['Age of pregnant women', 'Age of pregnant men'])

df.T.boxplot()
plt.subplots_adjust(bottom=0.25)
plt.xticks(rotation=25)
plt.show()

在此处输入图片说明

vert=False stands # for "no vertical"

使用 by='categorical_feature name' 为每个级别制作框 plt.tight_layout() # 消除任何重叠的图(并非总是如此)当您掌握 Matplotlib 和 Pandas 时,它们真的很容易,并且您可以使用它们来制作强大的图。

matplotlib has a vert property which is set to True by default. matplotlib 有一个vert属性,默认设置为 True。 Change it to False将其更改为False

plt.boxplot(df["feature"], vert=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM