【问题标题】:How to shrink plot on x-axis in matplotlib?如何在 matplotlib 中缩小 x 轴上的绘图?
【发布时间】:2014-09-23 21:40:58
【问题描述】:

我看过几个例子,但情节的构造不同,我不知道如何使语法起作用。这是我的代码:

pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")
for i in range(0, len(list_of_data)):
  biorep = int(list_of_figure_key[i].split('.')[1])
  construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
  plot(time, list_of_data[i], color=color_dict[construct], linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )
  xlabel('time (hours)', fontsize=9)
  ylabel(ReadType, fontsize=9)
  xlim(min(time),max(time))
  legend(fontsize=8, loc='center left', bbox_to_anchor=(1, .5))
pdf_file.savefig()

它产生了一个美丽的图形,但图例太长并且超出了页面的边缘。我想缩小 x 轴上的图,以便图例适合作为 2 列图例。

图可以看这里:http://i.imgur.com/mvgzIhj.jpg

提前致谢!

【问题讨论】:

  • 回答你的问题 Python 标准缩进是四个空格而不是两个

标签: python matplotlib


【解决方案1】:

您可以使用ncol legend 属性创建一个两列图例。您可以通过在绘图上绘制轴并固定其大小来缩小绘图的宽度:

from matplotlib import pyplot as plt
fig = plt.figure()                      # initialize figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # add axis

要使此功能与您的代码一起使用,应该可以使用以下内容:

# import pyplot
from matplotlib import pyplot as plt

# set up filename to save it
pdf_file = PdfPages(sys.argv[1].split('.')[0] + "_graphs.pdf")

# set up axis object
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# plot your data
for i in range(0, len(list_of_data)):
    biorep = int(list_of_figure_key[i].split('.')[1])
    construct = int(list_of_figure_key[i].split('.')[0].split('_')[1])
    ax.plot(time, list_of_data[i], color=color_dict[construct],
        linestyle=linestyle_dict[biorep], label=list_of_figure_key[i] )

# modify axis limits and legend 
ax.set_xlabel('time (hours)', fontsize=9)
ax.set_ylabel(ReadType, fontsize=9)
ax.set_xlim(min(time),max(time))
ax.legend(fontsize=8, loc='upper left', bbox_to_anchor=(1, .5), ncol=2)

# save final figure
plt.savefig(pdf_file)

在您的代码中,您在 for 循环的每次迭代中重新制作图例、限制和图例,以及保存然后覆盖 pdf 图像。这不是必需的——你可以在最后做一次。

更多图例提示,this post 很方便。 This one 也很有帮助。

【讨论】:

  • @Ajean 我已经编辑了回复以解决您提到的问题——如果您认为还有什么可以改进的,请告诉我!
  • @rebeccaroisin 你太随和了,喜欢它!你的麻烦是你的赞成票
  • @rebeccaroisin - 谢谢,add_axes 正是我想要的。也感谢你捕捉到循环,它现在运行得更快了。
猜你喜欢
  • 2019-02-26
  • 2020-06-09
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
相关资源
最近更新 更多