我必须在多个 y 轴上绘制线条。然而,在情节上,轴的生成go.Layout
非常冗长,就像plotly文档中的这个例子一样:https://plot.ly/python/multiple-axes/ https://plot.ly/python/multiple-axes/
layout = go.Layout(
title='multiple y-axes example',
width=800,
xaxis=dict(
domain=[0.3, 0.7]
),
yaxis=dict(
title='yaxis title',
titlefont=dict(
color='#1f77b4'
),
tickfont=dict(
color='#1f77b4'
)
## repeat for every new y-axis.
在 matplotlib 中,我喜欢通过生成所有不同的轴并在循环中处理绘图来保存代码,如下所示:
import matplotlib.pyplot as plt
import numpy as np
# generate dummy data
data = []
for i in range(5):
arr = np.random.random(10) * i
data.append(arr)
colors = ['black', 'red', 'blue', 'green', 'purple']
labels = ['label1', 'label2', 'label3', 'label4', 'label5']
# define other paramters (e.g. linestyle etc.) in lists
fig, ax_orig = plt.subplots(figsize=(10, 5))
for i, (arr, color, label) in enumerate(zip(data, colors, labels)):
if i == 0:
ax = ax_orig
else:
ax = ax_orig.twinx()
ax.spines['right'].set_position(('outward', 50 * (i - 1)))
ax.plot(arr, color=color, marker='o')
ax.set_ylabel(label, color=color)
ax.tick_params(axis='y', colors=color)
fig.tight_layout()
plt.show()
由于对象生成中使用的字典语法,我似乎无法使类似的东西在情节中工作。我尝试提前通过循环生成轴字典并将其传递给go.Layout
但没有成功。
如果有人能指出一种减少冗余的优雅方法,我们将不胜感激。
祝一切顺利,并提前致谢。