python - 脚注/注释与 xlabel 重叠
问题描述
我的代码:
请向下滚动到##### Part where the question is related #####
import os
import string
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.getDirAbsPath import outputAbsPath
inputCSV = './output.csv'
# Plot importance when the number of intervals is 2.
interval = len(string.ascii_lowercase)
df = pd.read_csv(inputCSV, index_col=0)
df01 = df[['0', '1']]
bins = np.array_split(df01, len(df01) / interval)[1]
df01 = pd.DataFrame(bins)
xlabel = '(i)th interval'
ylabel = 'feature importance'
title = 'Feature importance in classifying genotypes (%i iterations)' % interval
outputPath = os.path.join(outputAbsPath(), 'featureImportance', 'accuracies.png')
footnote = footnote = 'Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. '
# Plotting
fig, ax = plt.subplots(figsize=(15, 11), tight_layout=True)
plt.subplots_adjust(hspace=1.0, wspace=0.02, bottom=0.17)
# Creating axes instance
bp = ax.boxplot(df, patch_artist=True,
notch='True')
# changing color and linewidth of
# whiskers
for whisker in bp['whiskers']:
whisker.set(color='#8B008B',
linestyle=":")
# changing color and linewidth of
# caps
for cap in bp['caps']:
cap.set(color='#8B008B')
# changing color and linewidth of
# medians
for median in bp['medians']:
median.set(color='red')
# changing style of fliers
for flier in bp['fliers']:
flier.set(marker='D',
color='#e7298a',
alpha=0.5)
# x-axis labels
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
# Adding title
plt.title(title)
fig.subplots_adjust(bottom=0.2)
##### Part where the question is related #####
ft = plt.figtext(0, 0, footnote, wrap=True, va='bottom', fontsize=11)
#Have tried:
# ax.annotate(footnote, (0,-0.2), xycoords='figure fraction')
# plt.subplots_adjust(hspace=1.0, wspace=0.02, bottom=0.17)
# fig.subplots_adjust(bottom=0.2)
plt.tight_layout()
##### Part where the question is related #####
fig.savefig(outputPath)
# pickle.dump(fig, open((outputPath + '.fig.pickle'), 'wb'))
# show plot
fig.show()
print('%s saved.' % outputPath)
我一直让 xlabel 覆盖脚注。我尝试了几乎所有可以在网上找到的解决方案。有人可以让我知道如何在图表中添加长脚注吗?格式必须与论文中的一样。左右对齐图形的边缘(不是图形大小)。左对齐但跨越,以便除最后一行之外的行跨越以填充整行。
非常感谢您!:)
解决方案
使用这个出色的要点和宽度计算的小修复并手动设置底部焊盘(您可以使用交互式绘图后端获得正确的值,您可以在其中调整边框)我们得到:
import matplotlib.pyplot as plt
import matplotlib as mpl
fig,ax = plt.subplots()
ax.plot([1,2])
ax.set_xlabel('x-label')
fig.subplots_adjust(bottom=0.275)
footnote = 'Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. Classified with mean step up height as the model\'s input. '
#https://gist.github.com/dneuman/90af7551c258733954e3b1d1c17698fe
class WrapText(mpl.text.Text):
"""
WrapText(x, y, s, width, widthcoords, **kwargs)
x, y : position (default transData)
text : string
width : box width
widthcoords: coordinate system (default screen pixels)
**kwargs : sent to matplotlib.text.Text
Return : matplotlib.text.Text artist
"""
def __init__(self,
x=0, y=0, text='',
width=0,
widthcoords=None,
**kwargs):
mpl.text.Text.__init__(self,
x=x, y=y, text=text,
wrap=True,
clip_on=False,
**kwargs)
if not widthcoords:
self.width = width
else:
a = widthcoords.transform_point([(0,0),(width,0)])
self.width = a[1][0]-a[0][0]
def _get_wrap_line_width(self):
return self.width
trans = mpl.transforms.blended_transform_factory(
ax.transAxes, fig.transFigure)
wtxt = WrapText(0, 0, footnote, width=1, va='bottom',
widthcoords=ax.transAxes, transform=trans)
ax.add_artist(wtxt)
plt.show()
推荐阅读
- maven - Maven 包含由该构建生成的 JAR
- android - Kotlin:从自身/内部引用匿名对象(通过this)
- amazon-cloudformation - 在嵌套的 cloudformation 堆栈中共享价值上游可能吗?
- python - 如何使装饰器对调试器透明
- javascript - 为什么 JSON.parse() 会在元素前面添加数字?
- biztalk - 您可以在 BizTalk 2006 中使用“HAT”查看邮件正文吗?
- python - Celery group.apply_async().join() 永远不会返回
- ionic-framework - 无法在 ionic 中添加 android 平台
- salesforce - SSO 到 Salesforce 的动态门户
- javascript - reactjs——解决setState异步问题