从文档中:
默认转换指定文本位于数据坐标中,或者,您可以指定轴坐标中的文本(0,0 为左下角,1,1 为右上角)。下面的示例将文本放置在轴的中心:
Run Code Online (Sandbox Code Playgroud)>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', ... verticalalignment='center', transform=ax.transAxes)
我可以同时 使用数据和轴坐标吗?分别对于x和y。
示例代码:
>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
... verticalalignment='center', transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)
另请参阅: 将文本放在 matplotlib 图的左上角
这是我当前的代码
values = pd.Series([False, False, True, True])
v_counts = values.value_counts()
fig = plt.figure()
plt.pie(v_counts, labels=v_counts.index, autopct='%.4f', shadow=True);
Run Code Online (Sandbox Code Playgroud)
目前,它仅显示百分比(使用autopct)
我想同时显示百分比和实际值(我不介意位置)
我正在为某些函数编写类型注释,但找不到注释预期类型为 的参数的最佳方法matplotlib.axes._axes.Axes。
我什至不确定我是否为预期为 类型的参数做了正确的事情pandas.core.frame.DataFrame。
def myfunc(
df: pd.DataFrame, # is this correct?
ax: matplotlib.axes._axes.Axes # do I have to use this?
) -> None:
# body of my function
Run Code Online (Sandbox Code Playgroud)
一些见解?
谢谢。
我有一个问题,matplotlib 似乎没有遵循 rcparams。这种情况尤其适用于文本:注释、轴标签、标题等。我会注意到我没有同时运行 Seaborn(已知 Seaborn 会干扰某些 matplotlib 设置)。
我正在使用Python 3.7.10、matplotlib 3.3.4和seaborn 0.11.1
例如,这是一个简单的情节陈述。
plt.plot([1,2,3], [1,2,3])
plt.title("Simple plot")
Run Code Online (Sandbox Code Playgroud)
请注意,绘图标题以及数字刻度标签均以粗体显示。如果您查看 matplotlib 的在线示例,它们都默认为非粗体。如果我显示 plt.rcParams 的内容,我会得到以下内容(请参阅帖子底部)。请注意,相关项目,例如 'figure.titleweight': 'normal'、'font.weight': 'normal' 是 'normal' 而不是 'bold'。它正在使用其他一些本地设置吗?
我试图在不提供额外设置的情况下使其正常工作。奇怪的是,默认字体(DejaVu Sans)似乎对字体粗细的变化没有响应,这样如果我输入命令
plt.title("Simple plot", fontdict={'fontweight': 'normal', 'weight': 'normal', 'family': 'sans-serif'})
Run Code Online (Sandbox Code Playgroud)
我得到同样的结果。但如果我选择衬线字体,我会得到
plt.title("Simple plot", fontdict={'fontweight': 'normal', 'weight': 'normal', 'family': 'serif'})
Run Code Online (Sandbox Code Playgroud)
现在,我想得到无衬线的结果,但不是粗体,没有额外的参数。我还检查了我的 matplotlibrc 文件,其中似乎没有任何内容可以覆盖这些默认值。我也尝试运行 plt.rcdefaults(),但没有帮助。这些大胆的设定从何而来?
RcParams({'_internal.classic_mode': False,
'agg.path.chunksize': 0,
'animation.avconv_args': [],
'animation.avconv_path': 'avconv',
'animation.bitrate': -1,
'animation.codec': 'h264',
'animation.convert_args': [],
'animation.convert_path': 'convert',
'animation.embed_limit': 20.0,
'animation.ffmpeg_args': [],
'animation.ffmpeg_path': 'ffmpeg',
'animation.frame_format': 'png',
'animation.html': 'none',
'animation.html_args': [], …Run Code Online (Sandbox Code Playgroud) 我一直在使用该ax.bar_label方法将数据值添加到条形图中。数字很大,例如143858918。如何使用该ax.bar_label方法向数据值添加逗号?我确实知道如何使用注释方法添加逗号,但如果可以使用bar_label,我不确定。是否可以使用fmt可用的关键字参数?
从matplotlib 3.4.0开始,Axes.bar_label方法允许标记条形图。
但是,标签格式选项适用于旧式格式,例如fmt='%g'
我怎样才能使它与新的样式格式一起工作,使我能够执行百分比、千位分隔符等操作: '{:,.2f}', '{:.2%}', ...
我首先想到的是以某种方式获取初始标签ax.containers,然后重新格式化它们,但它还需要适用于不同的条形结构、具有不同格式的分组条形等等。
我正在创建一个像这样的条形图:
gender = ['M', 'F']
numbers = [males,females]
bars = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
for i in range(len(numbers)):
plt.annotate(str(numbers[i]), xy=(gender[i],numbers[i]))
plt.show()
Run Code Online (Sandbox Code Playgroud)
我想用来plt.annotate在栏的顶部写下确切的值。但是,该值打印在右侧。可以把它移到中心吗?
我有代码可以轻松地自动处理着色和绘制多个图(对我来说)。我想让注释变得更容易:
目标:如果注释 xy 与前一个注释冲突,请向上移动 - 直到与其他注释不发生冲突。
如果有一个功能已经能够做到这一点那将是一个梦想,但我找不到。
否则 - 列出注释并在坐标系中获取其边界框的最佳方法是什么?
我有一个自动着色代码,如下所示:
if chain:
children = []
for child in Iplot.axes.get_children():
if (type(child) is not matplotlib.collections.PathCollection and
type(child) is not matplotlib.lines.Line2D):
continue
children.append(child)
col_step = 1.0/(len(children)+len(args))
for child in children:
child.set_color([Iplot.col,0,1-Iplot.col])
Iplot.col += col_step
Run Code Online (Sandbox Code Playgroud)
我可以对注释做类似的事情(更改 if 语句和第二个循环的主体),但是 1)我不喜欢这段代码 2)我希望存在更优雅的东西。
这是我使用的代码:
import matplotlib.pyplot as plt
plt.annotate(
# Label and coordinate
'Help here!', xy=(8, 0.4),xytext=(7.05, 0.6) ,
# Custom arrow
arrowprops=dict(arrowstyle='->',lw=1)
)
Run Code Online (Sandbox Code Playgroud)
xytext 坐标表示文本开始的坐标。如果设置不正确,箭头将不再垂直。现在,为了使箭头垂直,我需要手动找到变量 xytext 的正确 x 坐标(对于此文本,它似乎是 7.05)。但我能找到一种方法来表明我想要的命令吗?
您好,我正在尝试向我的 5 个类别和 2 个值(旧的和年轻的)添加百分比countplot。我尝试添加来自
如何在seaborn中的条形顶部添加百分比?
我的代码:
plt.figure(figsize =(7,5))
ax = sb.countplot(data = df_x_1, x = 'concern_virus', hue = 'age')
plt.xticks(size =12)
plt.xlabel('Level of Concern', size = 14)
plt.yticks(size = 12)
plt.ylabel('Number of People', size = 12)
plt.title("Older and Younger People's Concern over the Virus", size = 16)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right");
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_height()/total)
x = p.get_x() + p.get_width()
y = p.get_height()
ax.annotate(percentage, (x, y),ha='center')
plt.show()
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,百分比没有意义。
matplotlib ×10
plot-annotations ×10
python ×10
bar-chart ×3
seaborn ×3
countplot ×1
pandas ×1
pie-chart ×1
python-3.8 ×1
text ×1