为图表添加副标题

发布于 2024-08-03 20:49:04 字数 163 浏览 4 评论 0原文

我想为我的图表指定一个 18pt 大字体的标题,然后在其下方添加一个 10pt 小字体的副标题。我怎样才能在 matplotlib 中做到这一点?看来 title() 函数只接受具有单个 fontsize 属性的单个字符串。一定有办法做到这一点,但是怎么办呢?

I want to give my graph a title in big 18pt font, then a subtitle below it in smaller 10pt font. How can I do this in matplotlib? It appears the title() function only takes one single string with a single fontsize attribute. There has to be a way to do this, but how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

梦幻之岛 2024-08-10 20:49:04

我所做的是使用 title() 函数作为副标题,使用 suptitle() 作为主标题(它们可以采用不同的字体大小参数)。

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different font size arguments).

书信已泛黄 2024-08-10 20:49:04

虽然这不能为您提供与多种字体大小相关的灵活性,但向 pyplot.title() 字符串添加换行符可能是一个简单的解决方案;

plt.title('Really Important Plot\nThis is why it is important')

Although this doesn't give you the flexibility associated with multiple font sizes, adding a newline character to your pyplot.title() string can be a simple solution;

plt.title('Really Important Plot\nThis is why it is important')
锦欢 2024-08-10 20:49:04

这是一个实现 Floris van Vugt 答案(2010 年 12 月 20 日)的 pandas 代码示例。他说:

>我所做的是使用 title() 函数作为副标题,使用 subtitle() 函数作为>主标题(它们可以采用不同的字体大小参数)。希望有帮助!

import pandas as pd
import matplotlib.pyplot as plt

d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
      'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)

title_string = "This is the title"
subtitle_string = "This is the subtitle"

plt.figure()
df.plot(kind='bar')
plt.suptitle(title_string, y=1.05, fontsize=18)
plt.title(subtitle_string, fontsize=10)

注意:我无法对该答案发表评论,因为我是 stackoverflow 的新手。

This is a pandas code example that implements Floris van Vugt's answer (Dec 20, 2010). He said:

>What I do is use the title() function for the subtitle and the suptitle() for the >main title (they can take different fontsize arguments). Hope that helps!

import pandas as pd
import matplotlib.pyplot as plt

d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
      'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)

title_string = "This is the title"
subtitle_string = "This is the subtitle"

plt.figure()
df.plot(kind='bar')
plt.suptitle(title_string, y=1.05, fontsize=18)
plt.title(subtitle_string, fontsize=10)

Note: I could not comment on that answer because I'm new to stackoverflow.

八巷 2024-08-10 20:49:04

对我有用的解决方案是:

  • 使用 suptitle() 作为实际标题,
  • 使用 title() 作为副标题,并使用可选参数 y 进行调整code>:
    import matplotlib.pyplot as plt
    """
            some code here
    """
    plt.title('My subtitle',fontsize=16)
    plt.suptitle('My title',fontsize=24, y=1)
    plt.show()

两段文本之间可能存在一些令人讨厌的重叠。您可以通过调整 y 的值来解决此问题,直到得到正确的结果。

The solution that worked for me is:

  • use suptitle() for the actual title
  • use title() for the subtitle and adjust it using the optional parameter y:
    import matplotlib.pyplot as plt
    """
            some code here
    """
    plt.title('My subtitle',fontsize=16)
    plt.suptitle('My title',fontsize=24, y=1)
    plt.show()

There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y until you get it right.

很酷又爱笑 2024-08-10 20:49:04

我不认为有任何内置的东西,但是您可以通过在轴上方留出更多空间并使用 figtext

axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')

ha水平对齐

I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext:

axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')

ha is short for horizontalalignment.

没有你我更好 2024-08-10 20:49:04

只需使用 TeX 即可!这有效:

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

编辑:要启用 TeX 处理,您需要将“usetex = True”行添加到 matplotlib 参数:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

我想您的计算机上还需要一个可用的 TeX 发行版。所有详细信息均在此页面给出:

http://matplotlib.org/users/usetex.html

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html

哑剧 2024-08-10 20:49:04

正如此处所述,您可以使用matplotlib.pyplot.text对象来实现相同的效果结果:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)

As mentioned here, uou can use matplotlib.pyplot.text objects in order to achieve the same result:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)
伴我心暖 2024-08-10 20:49:04

这是我在考虑如何使用 matplotlib 来满足我的需求时编写的 hello world。它非常全面,可以满足您所有的标题和标签需求。

快速总结

以下是制作字幕的方法:只需使用固定在正确位置的常规图形文本框:

# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")

0.5 x 位置是左侧和右侧之间的中点。 0.9 y 位置将其从顶部稍微向下放置,以便它最终位于图标题下方。我们使用horizo​​ntalalignment="center"来确保它保持左右居中。

官方 matplotlib 文档:

  1. 对于 matplotlib.figure.text()https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.text
  2. 对于 matplotlib.pyplot.text(): < a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html" rel="nofollow noreferrer">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot .text.html

其他绘图功能和标题的摘要:

# Figure title (super-title)
fig.suptitle("Figure title", fontsize=16)
# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")
# Figure footer title
fig.text(0.5, 0.015, "Figure footer: see my website at www.whatever.com.",
         horizontalalignment="center")

# Plot title, axes, and legend
plt.title("Plot title")
plt.xlabel("x-axis label")
plt.ylabel("y-axis label")
plt.plot(x_vals, y_vals, 'r-o', label="Drag curve for Vehicle 1")
plt.legend()

# Plot point labels
plt.text(x+.2, y-1, f"({x} m/s, {y:.2f} N drag)",
         horizontalalignment="left", rotation=0)

完整、可运行的示例:

如何添加图形标题、图形副标题、图形页脚、图形标题、轴标签、图例标签和 (x, y ) Matplotlib 中的点标签:

在此处输入图像描述

来自我的 eRCaGuy_hello_world 存储库的plot_hello_world_set_all_titles_axis_labels_etc.py:

import matplotlib.pyplot as plt

# ----------------------------------
# 1. Create a new figure
# - Can be done multiple times to create multiple GUI windows of figures.
# ----------------------------------

# Create a new figure. Now, all calls to `plt.whatever()` will apply to this
# figure.
# - When done adding subplots below, you can create more figures using this call
#   if you want to create multiple separate GUI windows of figures.
fig = plt.figure()

# ----------------------------------
# 2. Add a plot or subplot to it.
# - You can use the `fig.add_subplot()` call below multiple times to add
#   multiple subplots to your figure.
# ----------------------------------
# Optional: make this plot a subplot in a grid of plots in your figure
# fig.add_subplot(2, 2, 1) # `2` rows x `2` columns of plots, this is subplot `1`

# List of x values
x_vals = [1, 2, 3, 4, 5, 6, 7]
# Use a "list comprehension" to make some y values
y_vals = [val**2 for val in x_vals]

# Plot your x, y values: red (`r`) line (`-`) with circles (`o`) for points
plt.plot(x_vals, y_vals, 'r-o', label="Drag curve for Vehicle 1")
plt.legend()
plt.xlabel("x-axis label")
plt.ylabel("y-axis label")
plt.title("Plot title")

# display (x, y) values next to each point in your plot or subplot
for i, x in enumerate(x_vals):
    y = y_vals[i]
    # for your last 2 points only
    if i >= len(x_vals) - 2:
        plt.text(x-.2, y-1, f"({x} m/s, {y:.2f} N drag)",
                 horizontalalignment="right", rotation=0)
    # for all other points
    else:
        plt.text(x+.2, y-1, f"({x} m/s, {y:.2f} N drag)",
                 horizontalalignment="left", rotation=0)

# ----------------------------------
# 3. When all done adding as many subplots as you want to for your figure,
#    configure your figure title, subtitle, and footer.
# ----------------------------------

fig.suptitle("Figure title", fontsize=16)
# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")
# Figure footer title
fig.text(0.5, 0.015, "Figure footer: see my website at www.whatever.com.",
         horizontalalignment="center")
# Important!:
# 1. Use `top=0.8` to bring the top of the plot down to leave some space above
# the plot for the figure subtitle to go above the plot title!
# 2. Use `bottom=0.2` to bring the bottom of the plot up to leave space for the
# figure footer.
plt.subplots_adjust(top=0.8, bottom=0.2)

# ----------------------------------
# 4. Finally, when done adding all of the figures you want to, each with as many
#    subplots as you want, call this to show all figures!
# ----------------------------------

plt.show()

另请参阅

  1. Matplotlib:在图表上每个点旁边显示值
    1. 我对此的回答也是:如何绘制每个点的(x, y)文本使用 plt.text(),并使用自定义文本格式处理第一个和最后一个点
  2. 所有 matplotlib.org 文档。例如: https://matplotlib.org/stable/api/_as_gen/ matplotlib.pyplot.subplots_adjust.html

Here's a hello world I wrote as I was figuring out how to use matplotlib for my needs. It's pretty thorough, for all your title and label needs.

Quick summary

Here's how to do a subtitle: just use a regular figure text box stuck in the right place:

# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")

The 0.5 x-location is the halfway point between the left and the right. The 0.9 y-location puts it a little down from the top, so that it will end up under the Figure title. We use horizontalalignment="center" to ensure it stays centered left and right.

Official matplotlib documentation:

  1. For matplotlib.figure.text(): https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.text
  2. For matplotlib.pyplot.text(): https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html
  3. etc.

Summary of other plot features and titles:

# Figure title (super-title)
fig.suptitle("Figure title", fontsize=16)
# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")
# Figure footer title
fig.text(0.5, 0.015, "Figure footer: see my website at www.whatever.com.",
         horizontalalignment="center")

# Plot title, axes, and legend
plt.title("Plot title")
plt.xlabel("x-axis label")
plt.ylabel("y-axis label")
plt.plot(x_vals, y_vals, 'r-o', label="Drag curve for Vehicle 1")
plt.legend()

# Plot point labels
plt.text(x+.2, y-1, f"({x} m/s, {y:.2f} N drag)",
         horizontalalignment="left", rotation=0)

Full, runnable example:

How to add a figure title, figure subtitle, figure footer, plot title, axis labels, legend label, and (x, y) point labels in Matplotlib:

enter image description here

plot_hello_world_set_all_titles_axis_labels_etc.py from my eRCaGuy_hello_world repo:

import matplotlib.pyplot as plt

# ----------------------------------
# 1. Create a new figure
# - Can be done multiple times to create multiple GUI windows of figures.
# ----------------------------------

# Create a new figure. Now, all calls to `plt.whatever()` will apply to this
# figure.
# - When done adding subplots below, you can create more figures using this call
#   if you want to create multiple separate GUI windows of figures.
fig = plt.figure()

# ----------------------------------
# 2. Add a plot or subplot to it.
# - You can use the `fig.add_subplot()` call below multiple times to add
#   multiple subplots to your figure.
# ----------------------------------
# Optional: make this plot a subplot in a grid of plots in your figure
# fig.add_subplot(2, 2, 1) # `2` rows x `2` columns of plots, this is subplot `1`

# List of x values
x_vals = [1, 2, 3, 4, 5, 6, 7]
# Use a "list comprehension" to make some y values
y_vals = [val**2 for val in x_vals]

# Plot your x, y values: red (`r`) line (`-`) with circles (`o`) for points
plt.plot(x_vals, y_vals, 'r-o', label="Drag curve for Vehicle 1")
plt.legend()
plt.xlabel("x-axis label")
plt.ylabel("y-axis label")
plt.title("Plot title")

# display (x, y) values next to each point in your plot or subplot
for i, x in enumerate(x_vals):
    y = y_vals[i]
    # for your last 2 points only
    if i >= len(x_vals) - 2:
        plt.text(x-.2, y-1, f"({x} m/s, {y:.2f} N drag)",
                 horizontalalignment="right", rotation=0)
    # for all other points
    else:
        plt.text(x+.2, y-1, f"({x} m/s, {y:.2f} N drag)",
                 horizontalalignment="left", rotation=0)

# ----------------------------------
# 3. When all done adding as many subplots as you want to for your figure,
#    configure your figure title, subtitle, and footer.
# ----------------------------------

fig.suptitle("Figure title", fontsize=16)
# Figure subtitle
fig.text(0.5, 0.9, "Figure subtitle", horizontalalignment="center")
# Figure footer title
fig.text(0.5, 0.015, "Figure footer: see my website at www.whatever.com.",
         horizontalalignment="center")
# Important!:
# 1. Use `top=0.8` to bring the top of the plot down to leave some space above
# the plot for the figure subtitle to go above the plot title!
# 2. Use `bottom=0.2` to bring the bottom of the plot up to leave space for the
# figure footer.
plt.subplots_adjust(top=0.8, bottom=0.2)

# ----------------------------------
# 4. Finally, when done adding all of the figures you want to, each with as many
#    subplots as you want, call this to show all figures!
# ----------------------------------

plt.show()

See also

  1. Matplotlib: Display value next to each point on chart
    1. And my answer on this too: How to plot the (x, y) text for each point using plt.text(), and handle the first and last points with custom text formatting
  2. All of the matplotlib.org documentation. Ex: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
凡尘雨 2024-08-10 20:49:04

在 matplotlib 中使用以下函数设置字幕

fig, ax = plt.subplots(2,1, figsize=(5,5))
ax[0, 0].plot(x,y)
ax[0, 0].set_title('text')

In matplotlib use the below function to set the subtitle

fig, ax = plt.subplots(2,1, figsize=(5,5))
ax[0, 0].plot(x,y)
ax[0, 0].set_title('text')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文