【问题标题】:How do I center the outputs on a Python Jupyter notebook?如何将输出集中在 Python Jupyter 笔记本上?
【发布时间】:2018-01-22 02:42:41
【问题描述】:

我有一个在 Jupyter Notebook 中创建的报告。出于美学原因,我希望输出(图)居中。

我已经尝试过这里给出的答案:

Centering output on IPython notebook

但是这个不起作用。

我确实发现这个适用于 Stackoverflow (Center align outputs in ipython notebook)

CSS = """
.output {
    align-items: center;
}
"""

HTML('<style>{}</style>'.format(CSS))

但是,虽然它使绘图居中,但当绘图很宽且不需要居中时,它会扩展它并使其比我不想要的页面更宽。我已经尝试像它说的那样调整输出边距区域,但是它要么再次将其推向左侧,要么将其挤压到需要滚动条的程度(我又不想那样)

有人有什么建议吗?我认为这将是标准且简单的,但显然不是(如果无法实现我想要的,仅将代码块居中的方法将是一个完美的解决方法?)

即将此表居中:

这是由这段代码产生的:

df = pd.DataFrame(a01) 

new_df01 = df[['Call','FirstReceivedDate','Value']]
new_df01['month'] = pd.Categorical(new_df01['FirstReceivedDate'].dt.strftime('%b'), 
                                         categories=vals, ordered=True) 

groupA01 = new_df01.groupby(['Call']).agg({'Value':sum, 'FirstReceivedDate':'count'}).rename(columns={'FirstReceivedDate':'Count'})
groupA01['Value'] = groupA01['Value'].map('{:,.2f}'.format)

def hover(hover_color="#F1C40F"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

styles2 = [
    hover(),
    dict(selector="th", props=[("font-size", "80%"),
                               ("font-family", "Gill Sans MT"),
                               ("color",'white'),
                               ('background-color', 'rgb(11, 48, 79)'),
                               ("text-align", "center")]),
    dict(selector="td", props=[("font-size", "75%"),
                               ("font-family", "Gill Sans MT"),
                               ("text-align", "center")]),
    dict(selector="tr", props=[("line-height", "11px")]),
    dict(selector="caption", props=[("caption-side", "bottom")])
]


html2 = (groupA01.style.set_table_styles(styles2)
          .set_caption(""))
html2

谢谢!

添加代码以显示热图的绘制:

dfreverse = df_hml.values.tolist()
dfreverse.reverse()

colorscale = [[0,'#FFFFFF'],[0.5, '#454D59'], [1, '#F1C40F']]

x = [threeYr,twoYr,oneYr,Yr]
y = ['March', 'February', 'January', 'December', 'November', 'October', 'September', 'August', 'July', 'June', 'May', 'April']
z = dfreverse

hovertext = list()
for yi, yy in enumerate(y):
    hovertext.append(list())
    for xi, xx in enumerate(x):
        hovertext[-1].append('Count: {}<br />{}<br />{}'.format(z[yi][xi],yy, xx))

data = [plotly.graph_objs.Heatmap(z=z,
                                  colorscale=colorscale,
                                  x=x,
                                  y=y,
                                  hoverinfo='text',
                                  text=hovertext)]

layout = go.Layout(
    autosize=False,
    font=Font(
        family="Gill Sans MT",
        size = 11
    ),
    width=600,
    height=450,
    margin=go.Margin(
        l=0,
        r=160,
        b=50,
        t=100,
        pad=3
    ),
        xaxis=dict(
        title='',
        showgrid=False,
        titlefont=dict(
           # family='Gill sans, monospace',
            size=12,
            #color='#7f7f7f'
        ),
        showticklabels=True,
        tickangle=25,
        tickfont=dict(
            family="Gill Sans MT",
            size=12,
            color='black'
        ),
    ),
    yaxis=dict(
        title='',
        showgrid=False,
        titlefont=dict(
            #family='Gill sans',
            #size=12,
            #color='#7f7f7f'
        ),
        showticklabels=True,
        tickangle=25,
        tickfont=dict(
            family="Gill Sans MT",
            size=12,
            color='black'
        ),
)
)

fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.iplot(fig,config={"displayModeBar": False},show_link=False,filename='pandas-heatmap')

【问题讨论】:

  • 您只是想将输出在笔记本的实时版本中居中,还是在nbconvert 将其转换为例如HTML、PDF?还是您希望它以两种情况为中心?
  • 您好,谢谢您的回复!当您通过笔记本将其导出为 html 时,我希望它使输出居中 :)

标签: python jupyter-notebook plotly


【解决方案1】:

请试用此类以使您的图表居中,因为没有提供数据框,我正在创建一个带有随机数据框的图,以展示该类的功能。请检查一下。

代码:

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.display import display, HTML
from plotly.graph_objs import *
import numpy as np
init_notebook_mode(connected=True)

display(HTML("""
<style>
.output {
    display: flex;
    align-items: center;
    text-align: center;
}
</style>
"""))
iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])
iplot([Box(y = np.random.randn(50), showlegend=False) for i in range(45)], show_link=False)
x = np.random.randn(2000)
y = np.random.randn(2000)
iplot([Histogram2dContour(x=x, y=y, contours=Contours(coloring='heatmap')),
       Scatter(x=x, y=y, mode='markers', marker=Marker(color='white', size=3, opacity=0.3))], show_link=False)

输出:

【讨论】:

  • 谢谢 Naren,现在去看看 :)
  • 嘿,首先感谢您的帮助,您的代码确实使输出居中,但就像我之前的问题一样,当您将其导出为 HTML 时,由于某种原因它会挤压图表并添加水平滚动bar :/... 我真的不知道为什么。
  • @ScoutEU 让我导出并检查
  • 好的,谢谢。作为正在发生的事情的一个例子......这是我的 HTML 导出的图片 (imgur.com/oLFdISa)
  • @ScoutEU你没有提供绘图功能,至于你是如何使用plotly来绘制数据的,我说的是你最后使用的iplot函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 2020-12-27
  • 2018-01-12
  • 1970-01-01
  • 2020-12-23
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多