首页 > 解决方案 > 如何在 Google Colab 中对齐输出(图表)?

问题描述

有没有办法在 Google Colab 中对齐代码输出?

在 Jupyter Notebook 中,我使用

from IPython.display import HTML, display

display(HTML("""
<style>
.output {
    display: flex;
    align-items: center;
    text-align: center;
}
</style>
"""))

这使代码的输出(例如绘图图表)与中心对齐。Google Colab 没有抛出任何错误,但它完全忽略了代码,并且所有内容仍然保持对齐。有人遇到这个问题并解决了吗?

非常感谢!

标签: pythonoutputalignmentgoogle-colaboratory

解决方案


Colab 输出在自己的 iframe 中,因此在一个输出中定义的 CSS 不会影响其他输出的显示。此外,Colab 中单元格输出的 DOM 结构与 Jupyter notebook 或 JupyterLab 中的略有不同(它们彼此之间略有不同)。

尝试将其放在与您正在创建的图表相同的单元格中:

display(HTML("""
<style>
#output-body {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
"""))

例子:

from IPython.display import HTML, display

display(HTML("""
<style>
#output-body {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
"""))

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip",
                width=300, height=300)

fig.show()
fig.show()

在此处输入图像描述


推荐阅读