标题,刻度,轴标签,matplotlib中未显示任何内容

时间:2020-05-04 17:59:22

标签: python python-3.x matplotlib

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

def plot_graph():
  fig = plt.figure()
  data = [[top3_empsearch, top5_empsearch, top7_empsearch], [top3_elastic, top5_elastic, top7_elastic]]
  X = np.arange(3)
  ax = fig.add_axes([0, 0, 1, 1])
  ax.bar(X + 0.00, data[0], color='b', width=0.25)
  ax.bar(X + 0.25, data[1], color='g', width=0.25)
  ax.set_ylabel('Accuracy (in %)')
  plt.title('Percentage accuracy for selected result in Top-3, Top-5, Top-7 in employee search vs elastic search')
  plt.yticks(np.arange(0, 101, 10))
  colors = {'empsearch':'blue', 'elastic':'green'}
  labels = list(colors.keys())
  handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]

  plt.legend(handles, labels)
  plt.style.use('dark_background')
  plt.show()

plot_graph()

此代码的结果是-> enter image description here

没有刻度,没有标签,没有标题,什么都看不见,我很困惑。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

唯一的问题是在这一行:

ax = fig.add_axes([0, 0, 1, 1])

在参考书目(https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.figure.Figure.html)中,您会看到add_axes()函数的第一个参数是“ rect”,这是指新书的尺寸[左,底,宽,高]轴,全部以图形宽度和高度的分数表示。因此,在您的代码中,您恰好给出了图形的尺寸,因此标题,刻度线,标签...在那里但被隐藏。因此,您必须留一些空间,以减小绘图的尺寸。您可以通过修改来做到这一点:

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

或者,您也可以将该行替换为:

ax = fig.add_subplot(1,1,1) 

并且结果应该相同。

这是我的结果:

enter image description here