有没有办法阻止 Plotly 在向折线图添加标记时更改 x 轴上的填充。 请参阅下面的两个片段。唯一的区别是第 24 行,其中
'lines'
更改为 'lines+markers'
。
第一个没有标记的片段:
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
var layout = {
xaxis: {
showticklabels: true,
tickmode: 'auto',
nticks: 15,
tickangle: 45,
rangemode: 'tozero',
},
};
var trace1 = {
x: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8'],
y: [10, 15, 13, 17, 10, 15, 13, 17],
type: 'scatter',
mode: 'lines',
};
var data = [trace1];
Plotly.newPlot('myDiv', data, layout);
</script>
</body>
带有标记的第二个片段:
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
var layout = {
xaxis: {
showticklabels: true,
tickmode: 'auto',
nticks: 15,
tickangle: 45,
rangemode: 'tozero',
},
};
var trace1 = {
x: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8'],
y: [10, 15, 13, 17, 10, 15, 13, 17],
type: 'scatter',
mode: 'lines+markers',
};
var data = [trace1];
Plotly.newPlot('myDiv', data, layout);
</script>
</body>
这有点令人困惑,因为它实际上是 y 轴关闭的。 无论如何,可以通过将
yaxis
设置为 showgrid: false
然后偏移 yaxislayer-above
来重新定位标签来解决此问题。
这可以用 css 来完成,就像我一样,或者用 Javascript 来完成。
我在这里可能没有相同的像素(设置为 102px),但你应该明白。
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
.yaxislayer-above {
transform: translate(102px,100px);
}
</style>
</head>
<body>
<div id="myDiv">
</div>
<script>
var layout = {
yaxis: {
showgrid: false,
},
xaxis: {
showticklabels: true,
tickmode: 'auto',
nticks: 15,
tickangle: 45,
rangemode: 'tozero',
},
};
var trace1 = {
x: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8'],
y: [10, 15, 13, 17, 10, 15, 13, 17],
type: 'scatter',
mode: 'lines+markers',
};
var data = [trace1];
Plotly.newPlot('myDiv', data, layout);
</script>
</body>
我遇到了同样的问题,我找到的解决方案是将
autorange
设置为 false
AND 指定 x 轴 range
。请参阅:https://plot.ly/javascript/reference/#layout-xaxis-range
固定示例:
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
var layout = {
xaxis: {
showticklabels: true,
tickmode: 'auto',
nticks: 15,
tickangle: 45,
rangemode: 'tozero',
range: [0, 7]
},
};
var trace1 = {
x: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8'],
y: [10, 15, 13, 17, 10, 15, 13, 17],
type: 'scatter',
mode: 'lines+markers',
};
var data = [trace1];
Plotly.newPlot('myDiv', data, layout);
</script>
</body>
指定
range
有效,但我注意到,当您使用模式栏按钮或鼠标双击自动缩放轴时,会自动重新添加填充(至少在 python 中)。所以我宁愿使用 autorangeoptions_maxallowed 和 autorangeoptions_minallowed 以及我想要的范围的上限和下限。