python - Plotly-Python:如何制作有间隙的 y 轴?
问题描述
感谢 Plotly-R 的原始问题。以下将重点介绍 Python。
是否可以创建一个绘图条形图,例如来自以下网站的任何图表:plotly.com/r/bar-charts/但 Y 轴有间隙(断开)?下面附上一个来自(ggplot2,我相信)的例子:
解决方案
据我所知,plotly 没有任何内置功能可以做到这一点。但是,如果您:
- 使用 make_
subplots(rows=2, cols=1, vertical_spacing = <low>)
, - 将相同的轨迹添加到图形位置
[1, 1]
和[2, 1]
, - 删除 x 轴标签
[1, 1]
, 和 - 调整图形位置的 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()
推荐阅读
- c# - 如何在 .Net C# 中存储和检索 Windows 注册表中的类数组?
- python - 使用 kivy 上传文件
- javascript - 递归 axios.get() 返回空数组
- mysql - 第 1 行的 CSV 输入中的列数无效
- lua - 将 IUP 库与 Lua For Windows 一起使用,如何强制 iup.getparam 和其他预定义对话框始终位于顶部?
- html - 为什么我的 HTML 文件没有显示在浏览器上?
- javascript - 带有 Socket.IO 和命名空间的 NodeJs-Cluster
- ruby-on-rails - 你能把一堆 Mongoid 集合聚合成一个批量事务吗?
- webdriver-io - 使用 webdriverio 查找所有可点击元素
- c# - IGDB API v4 搜索游戏