问题
As a follow on to a previous question
Suppose I want to show a set of bars, where each bar could be one of the choices: A, B, or C, each which has a different color. I would like to show the bars, but also if none the bars fall into a particular category still have that category show up in the legend. Unfortunately the categories without colors seem to get dropped. Notice in this example how the category labeled 'C' which should be blue is dropped from the legend:
data = [
{
x: [1, 3, 4],
y: [20, 14, 23],
type: 'bar',
name: 'A',
marker: {color: '#00FFFF'}},
{
x: [2, 5, 6],
y: [8, 6, 2],
type: 'bar',
name: 'B',
marker: {color: '#FF00FF'}},
{
x: [],
y: [],
type: 'bar',
name: 'C'
marker: {color: '#FF0000'}}]
How would I be able to make sure C (or any color without data) always shows up?
回答1:
Traces with empty data arrays are assumed to be not visible. This is equivalent to setting visible: false
in the trace object.
You can trick plotly by entering null
values in the data arrays:
data = [{
x: [1, 3, 4],
y: [20, 14, 23],
type: 'bar',
name: 'A',
marker: {color: '#00FFFF'}
}, {
x: [2, 5, 6],
y: [8, 6, 2],
type: 'bar',
name: 'B',
marker: {color: '#FF00FF'}
}, {
x: [null],
y: [null],
type: 'bar',
name: 'C'
marker: {color: '#FF0000'}
}]
which gives
回答2:
You could add initialize the third trace with a datapoint with zero height:
{'x': [0], 'y': [0], 'type': 'bar'}
interactive example: https://plot.ly/~chris/16792.embed
you'll also probably want to remove the hover text if there is no data. customize hover text with hoverinfo (https://plot.ly/python/reference/#bar-hoverinfo).
{'x': [0], 'y': [0], 'type': 'bar', 'hoverinfo': 'none'}
example chart: https://plot.ly/~chris/16795.embed
来源:https://stackoverflow.com/questions/33112854/plotly-have-trace-without-data-in-legend