首页 > 解决方案 > Plotly-Python:如何制作有间隙的 y 轴?

问题描述

感谢 Plotly-R 的原始问题以下将重点介绍 Python。


是否可以创建一个绘图条形图,例如来自以下网站的任何图表:plotly.com/r/bar-charts/但 Y 轴有间隙(断开)?下面附上一个来自(ggplot2,我相信)的例子:

在此处输入图像描述

标签: pythonplotlyplotly-python

解决方案


据我所知,plotly 没有任何内置功能可以做到这一点。但是,如果您:

  1. 使用 make_ subplots(rows=2, cols=1, vertical_spacing = <low>)
  2. 相同的轨迹添加到图形位置[1, 1][2, 1],
  3. 删除 x 轴标签[1, 1], 和
  4. 调整图形位置的 y 轴,[1, 1][2, 1]在定义的间隔内分别以所需的截止值开始和结束。

阴谋:

在此处输入图像描述

完整代码:

# imports
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots

# data
df = pd.DataFrame({'years': [1995, 1996, 1997, 1998, 1999, 2000,
                             2001, 2002, 2003, 2004, 2005, 2006,
                             2007, 2008, 2009, 2010, 2011, 2012],
                  'China': [219, 146, 112, 127, 124, 180, 236,
                            207, 236, 263,350, 430, 474, 1526,
                            488, 537, 500, 439],
                  'Rest of world': [16, 13, 10, 11, 28, 37,
                                        43, 55, 56, 88, 105, 156, 270,
                                        299, 340, 403, 549, 1499]})
df.set_index('years', inplace = True)

# colors and cut-offs
colors = px.colors.qualitative.Plotly
cut_interval = [600, 1400]

# subplot setup
fig = make_subplots(rows=2, cols=1, vertical_spacing = 0.04)
fig.update_layout(title = "USA plastic scrap exports (...with some made-up values)")

# Traces for [2, 1]
# marker_color=colors[i] ensures that categories follow the same color cycle
for i, col in enumerate(df.columns):
    fig.add_trace(go.Bar(x=df.index,
                    y=df[col],
                    name=col,
                    marker_color=colors[i],
                    legendgroup = col,
                    ), row=2, col=1)

# Traces for [1, 1]
# Notice that showlegend = False.
# Since legendgroup = col the interactivity is
# taken care of in the previous for-loop.
for i, col in enumerate(df.columns):
    fig.add_trace(go.Bar(x=df.index,
                    y=df[col],
                    name=col,
                    marker_color=colors[i],
                    legendgroup = col,
                    showlegend = False,
                    ), row=1, col=1)

# Some aesthetical adjustments to layout
fig.update_yaxes(range=[cut_interval[1], max(df.max()*1.1)], row=1, col=1)
fig.update_xaxes(visible=False, row=1, col=1)
fig.update_yaxes(range=[0, cut_interval[0]], row=2, col=1)

fig.show()

推荐阅读