使用表格格式的Matplotlib条形图

3
我在我的图表底部添加了一个表格,但是有一些问题需要解决:
  1. 右边的填充太多。
  2. 左边的填充太少。
  3. 底部没有填充。
  4. 单元格对于其中的文本来说太小了。
  5. 表格距离图表底部太近。
  6. 行名所属的单元格没有与条形图颜色相匹配。
我已经疯狂地调试了很久。能否有人帮我解决这些问题?
以下是代码(Python 3):
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# Set styles
plt.style.use(['seaborn-paper', 'seaborn-whitegrid'])
plt.style.use(['seaborn'])
sns.set(palette='colorblind')
matplotlib.rc("font", family="Times New Roman", size=12)

labels = ['n=1','n=2','n=3','n=4','n=5']
a = [98.8,98.8,98.8,98.8,98.8]
b = [98.6,97.8,97.0,96.2,95.4]
bar_width = 0.20
data = [a,b]
print(data)
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(labels)))
columns = ('n=1', 'n=2', 'n=3', 'n=4', 'n=5')

index = np.arange(len(labels))
plt.bar(index, a, bar_width)
plt.bar(index+bar_width+.02, b, bar_width)
plt.table(cellText=data,
          rowLabels=['a', 'b'],
          rowColours=colors,
          colLabels=columns,
          loc='bottom')

plt.subplots_adjust(bottom=0.7)

plt.ylabel('Some y label which effect the bottom padding!')
plt.xticks([])
plt.title('Some title')
plt.show()

这是输出结果:

enter image description here

更新

现在可以正常工作了,但如果有人遇到问题:请确保您不要使用IntelliJ SciView查看绘图及其更改,因为它无法准确表示更改并引入了一些格式问题!

1个回答

2

我认为您可以通过在创建表格时使用bbox来设置边界框来解决第一个问题,例如:

bbox=[0, 0.225, 1, 0.2]

参数为[left, bottom, width, height]

对于第二个问题(颜色),这是因为color数组与seaborn的着色不对应。您可以使用以下命令查询seaborn调色板:

sns.color_palette(palette='colorblind')

这将给出一个颜色列表,其中包括seaborn正在使用的颜色。

请查看下面的修改:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# Set styles
plt.style.use(['seaborn-paper', 'seaborn-whitegrid'])
plt.style.use(['seaborn'])
sns.set(palette='colorblind')
matplotlib.rc("font", family="Times New Roman", size=12)

labels = ['n=1','n=2','n=3','n=4','n=5']
a = [98.8,98.8,98.8,98.8,98.8]
b = [98.6,97.8,97.0,96.2,95.4]
bar_width = 0.20
data = [a,b]

colors = sns.color_palette(palette='colorblind')
columns = ('n=1', 'n=2', 'n=3', 'n=4', 'n=5')

index = np.arange(len(labels))
fig = plt.figure(figsize=(12,9))
plt.bar(index, a, bar_width)
plt.bar(index+bar_width+.02, b, bar_width)
plt.table(cellText=data,
          rowLabels=[' a ', ' b '],
          rowColours=colors,
          colLabels=columns,
          loc='bottom',
          bbox=[0, 0.225, 1, 0.2])

fig.subplots_adjust(bottom=0.1)

plt.ylabel('Some y label which effect the bottom padding!')
plt.xticks([])
plt.title('Some title')
plt.show()

我还将子图调整更改为subplot_adjust(bottom=0.1),因为否则它不会正确显示。以下是输出结果:

输出结果


1
谢谢。我尝试了您的修改,虽然看起来更漂亮,而且您还解决了一些问题(非常感谢!),但表格现在基本上出现在图形的中间:( - pookie
哇,折腾了几个小时后,我终于做到了。问题的一大部分是我一直在使用IntelliJ的“SciView”来查看图表...这导致格式不正确,因此进行调整非常困难!再次感谢! - pookie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接