You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Colab中居中对齐Jupyter单元格内的绘图

在Google Colab中居中Matplotlib绘图及输出文本的解决方法

我在Google Colab的Jupyter Notebook中生成了默认左对齐的Matplotlib绘图,代码如下:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1.320, 1.127, 0.997, 0.800, 0.587, 0.441, 0.323])
y = np.array([0.4064, 0.2886, 0.2347, 0.1516, 0.0854, 0.0485, 0.0375])

lx = np.log (x)
ly= np.log (y)


z = np.polyfit(lx, ly, 1)
p = np.poly1d(z)
plt.plot(lx, p(lx), 'r-.')

plt.xlim(-1.25, 0.4)
plt.ylim(-4, -0.5)


plt.plot(lx, ly, '.')
plt.title('The effect of length on the period')
plt.xlabel('Length (L) / lg(m)')
plt.ylabel('Period (T) / lg(s)')
plt.grid(True)
plt.legend(['Trend line', 'Experimental data'])
plt.show()

print(f"The equation of the curve is {p}")

希望绘图及相关输出文本都能居中显示,曾尝试以下代码但无效:

from IPython.core.display import HTML
HTML("""
<style>
.output_png {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
</style>
""")

可行解决方法

方法1:用HTML包裹输出内容

直接在输出时用<center>标签包裹绘图和文本,结合IPython.display模块实现:

import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display, HTML

x = np.array([1.320, 1.127, 0.997, 0.800, 0.587, 0.441, 0.323])
y = np.array([0.4064, 0.2886, 0.2347, 0.1516, 0.0854, 0.0485, 0.0375])

lx = np.log(x)
ly = np.log(y)

z = np.polyfit(lx, ly, 1)
p = np.poly1d(z)
plt.plot(lx, p(lx), 'r-.')

plt.xlim(-1.25, 0.4)
plt.ylim(-4, -0.5)

plt.plot(lx, ly, '.')
plt.title('The effect of length on the period')
plt.xlabel('Length (L) / lg(m)')
plt.ylabel('Period (T) / lg(s)')
plt.grid(True)
plt.legend(['Trend line', 'Experimental data'])

# 保存绘图并居中显示
fig = plt.gcf()
plt.close()
display(HTML(f'<center>{fig.to_html()}</center>'))

# 居中显示文本输出
display(HTML(f'<center>The equation of the curve is {p}</center>'))

方法2:修改全局输出容器的CSS

Colab的输出元素结构有更新,使用更精准的CSS选择器可以覆盖默认样式:

from IPython.core.display import HTML
HTML("""
<style>
/* 居中所有输出内容容器 */
div.output_area {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}
/* 确保图片和文本块内部也居中 */
div.output_png, div.output_text {
    text-align: center;
}
</style>
""")

运行这段代码后,再执行原有绘图代码,所有输出(包括图片和文本)都会自动居中。

方法3:调整Matplotlib绘图布局(仅针对绘图本身)

如果只关注绘图内容在画布中的居中,可以手动调整子图位置:

plt.figure(figsize=(8,6))
ax = plt.gca()

# 原有绘图代码...
z = np.polyfit(lx, ly, 1)
p = np.poly1d(z)
plt.plot(lx, p(lx), 'r-.')
plt.xlim(-1.25, 0.4)
plt.ylim(-4, -0.5)
plt.plot(lx, ly, '.')
plt.title('The effect of length on the period')
plt.xlabel('Length (L) / lg(m)')
plt.ylabel('Period (T) / lg(s)')
plt.grid(True)
plt.legend(['Trend line', 'Experimental data'])

# 调整子图位置,参数为[左偏移, 下偏移, 宽度, 高度],按需修改让内容居中
box = ax.get_position()
ax.set_position([0.15, 0.15, 0.7, 0.7])

plt.show()

此方法仅调整绘图区域,文本输出仍需配合前两种方法实现居中。

内容的提问来源于stack exchange,提问作者Tim Hulland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 05:20:07