简体   繁体   English

Python Pandas 和 Matplotlib - 如何控制图形与文本标签的相对大小?

[英]Python Pandas and Matplotlib - How can I control the relative size of the figure to text labels?

Here is a figured produced by Python Pandas + Matplotlib这是由 Python Pandas + Matplotlib 生成的数字

pandas 和 matplotlib 条形图

The problem is obvious: The x-axis labels are too large relative to the overall figure size.问题很明显:x 轴标签相对于整个图形大小来说太大了。

There are two ways to solve this:有两种方法可以解决这个问题:

  • Increase the overall figure size, keeping the label font size the same增加整体图形大小,保持 label 字体大小不变
  • Reduce the label font size while keeping the figure size the same减小 label 字体大小,同时保持图形大小不变

I am saving the output as pdf. I would ideally like to use the first option, as when I open this file on my computer, the actual screen rendered size is about 400 pixels wide, which isn't very large.我将 output 保存为 pdf。理想情况下,我想使用第一个选项,因为当我在计算机上打开此文件时,实际屏幕渲染大小约为 400 像素宽,不是很大。 But this may not be possile when saving as pdf?但这在保存为 pdf 时可能无法实现?

The code relevant is just two lines.相关代码只有两行。 data_age created from a Pandas dataframe. data_age从 Pandas dataframe 创建。

    # data is a Panadas dataframe, one of the columns is `'age'`.
    data_age = data['age'].value_counts().sort_index()

    plot = data_age.plot.bar()
    pplt.savefig('age.pdf')

I searched around to find a solution to what I would have assumed would be a commonly encountered problem.我四处寻找解决方案,以解决我认为是常见问题的问题。 I then went and read the documentation for matplotlib. There was an option dpi but this doesn't seem to have any effect when writing to a pdf file - which isn't surprising since pdf isn't a rasterized format.然后我去阅读 matplotlib 的文档。有一个dpi选项,但在写入 pdf 文件时这似乎没有任何效果——这并不奇怪,因为 pdf 不是光栅化格式。

You should use the ax keyword argument paired with a matplotlib figure.您应该将 ax 关键字参数与 matplotlib 数字配对使用。 Usage is as follows:用法如下:

# create a matplotlib figure and set figsize
my_wider_figure, my_ax = plt.subplots(figsize=(15,10))

data_age.plot.bar(ax=my_ax)

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

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