matplotlib 如何使用plt.gcf()访问图形后更改图的颜色?[重复]

sr4lhrrt  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(137)

此问题已在此处有答案

How does plt.gca work internally(2个答案)
How to change the plot line color from blue to black(3个答案)
上个月关门了。
我有以下代码:

  1. import numpy as np
  2. from fitter import Fitter
  3. from matplotlib import pyplot as plt
  4. randomData = np.random.normal(0, 1, 1000)
  5. def plotOfFittedDistributions(data):
  6. f = Fitter(data, distributions=['gamma', "norm", 'invgauss'], timeout=100)
  7. f.fit()
  8. f.hist()
  9. f.plot_pdf()
  10. ax = plt.gcf()
  11. return ax
  12. a = plotOfFittedDistributions(data=randomData)
  13. a

可以看出,我使用plt.gcf()访问了当前图形。是否可以在使用plt.gcf()访问后更改绘图的颜色?因此,我想在创建后访问具有多个绘图的单个图形,然后更改其颜色。
目前我有这个,它改变了颜色,但非常'丑陋'的代码:

  1. def colorShift(fig, newColor):
  2. tracker = []
  3. for i in range(0, len(fig.gca().get_children())):
  4. if type(fig.gca().get_children()[i]) == matplotlib.patches.Rectangle:
  5. tracker.append(i)
  6. for i in tracker[:len(tracker)-1]:
  7. fig.gca().get_children()[i].set_color(newColor)
up9lanfz

up9lanfz1#

我找到了答案:

  1. plt.gca().get_lines()[0].set_color("Purple")
  2. plt.gca().get_lines()[1].set_color("Yellow")
  3. plt.gca().get_lines()[2].set_color("Grey")
  4. myLegend = plt.gca().get_legend()
  5. myLegend.legend_handles[0].set_color('Purple')
  6. myLegend.legend_handles[1].set_color('Yellow')
  7. myLegend.legend_handles[2].set_color('Grey')

相关问题