pandas 熊猫直方图标签和标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32685185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas histogram Labels and Title
提问by DJV
I'm trying to put x- and y-axis labels as well as a title on a three-panel histogram I have created through Pandas, but can't seem to place it correctly. The only result I've gotten in the title and an x-axis label on the very last of the three graphs. I want one overall title, xlabel and ylabel. The code that makes the plot is below. Any suggestions?
我正在尝试将 x 轴和 y 轴标签以及标题放在我通过 Pandas 创建的三面板直方图上,但似乎无法正确放置。我在标题中得到的唯一结果和三个图表中最后一个的 x 轴标签。我想要一个整体标题,xlabel 和 ylabel。制作情节的代码如下。有什么建议?
df1.hist(column='human_den',by='region',sharex=True,sharey=True,layout=(1,3))
回答by Kevin
Following along from the accepted answer here, use subplotsto create Figureand axisobjects instances.
遵循此处接受的答案,用于subplots创建Figure和axis对象实例。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# random data
df1 = pd.DataFrame(columns=['human_den','region'])
df1['human_den'] = np.random.rand(100)
df1['region'] = np.random.choice(['Northeast', 'South', 'Midwest'], size=100)
# set up figure & axes
fig, axes = plt.subplots(nrows=1, ncols=3, sharex=True, sharey=True)
# drop sharex, sharey, layout & add ax=axes
df1.hist(column='human_den',by='region', ax=axes)
# set title and axis labels
plt.suptitle('Your Title Here', x=0.5, y=1.05, ha='center', fontsize='xx-large')
fig.text(0.5, 0.04, 'common X', ha='center')
fig.text(0.04, 0.5, 'common Y', va='center', rotation='vertical')
Notice, the keyword arguments sharex, sharey, and layoutare not assigned in df1.hist(), in favor of setting sharex, sharey, nrowsand ncolsin plt.subplotsto achieve similar effects. The important element is assigning df.hist()'s keyword argument, ax, to the previously initialized axesobject. The title can be set with suptitle.
请注意,关键字参数sharex,sharey以及layout未在分配df1.hist(),有利于环境sharex,sharey,nrows并ncols在plt.subplots实现类似的效果。重要的元素是将df.hist()的关键字参数 ,分配给ax先前初始化的axes对象。标题可以用suptitle设置。


