繁体   English   中英

我如何让matplotlib支持中文的**传奇**,而不仅支持colab上的“ ax.text”?

[英]How can I have matplotlib support Chinese for **legend**, not only for “ax.text” on colab?

此代码绘制成组的条形图效果很好。

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()


def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)

fig.tight_layout()

plt.show()

我想在传说中展示中文

此代码很好用,仅适用于plt.text而不是图例

import matplotlib as mpl
import matplotlib.font_manager as mfm

font_path = '/content/simsun.ttc'
prop = mfm.FontProperties(fname=font_path)

plt.text(0.5, 0.5, s=u'测试', fontproperties=prop)
plt.show()

这里放下字体

我试过将fontproperties = prop放在图例中,只会出错。

ax.legend(fontproperties=prop)

-------------------------------------------------- ------------------------- TypeError Traceback(最近的最近一次通话)位于()20 ax.set_xticks(x)21 ax.set_xticklabels(labels) ---> 22 ax.legend(fontproperties = prop)23 24

图例中的/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py(self,* args,** kwargs)421 if len(extra_args):422引发TypeError('传说仅接受两个非关键字参数')-> 423 self.legend_ = mlegend.Legend(self,handles,labels,** kwargs)424 self.legend _._ remove_method = self._remove_legend 425返回self.legend_

TypeError: init ()获得了意外的关键字参数'fontproperties'

这篇文章确实满足了我的需要,因为我正在未安装胶乳的google colab上运行。

很多帖子都在谈论支持中文支持ax.text而不是我所需要的方法,即传说

有任何想法吗?

检查文档

class matplotlib.legend.Legend(parent, handles, labels, loc=None, numpoints=None, markerscale=None, markerfirst=True, scatterpoints=None, scatteryoffsets=None, prop=None, fontsize=None, borderpad=None, labelspacing=None, handlelength=None, handleheight=None, handletextpad=None, borderaxespad=None, columnspacing=None, ncol=1, mode=None, fancybox=None, shadow=None, title=None, title_fontsize=None, framealpha=None, edgecolor=None, facecolor=None, bbox_to_anchor=None, bbox_transform=None, frameon=None, handler_map=None)

您将得到答案。

ax.legend(prop=prop)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM