简体   繁体   中英

Two line-plots with the same color in plotly

I am quiet new to plotly and usually use matplotlib . However, I have to use plotly this time (due to dash ). What I want is very simple with matplotlib , but I don't get it working with plotly : Two lines in the same figure that have the same color.

With matplotlib , this would look as follows:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 1, 2, 4], [0, 1, 2, 3], color='black')
ax.plot([0, 1, 2, 4], [10, 9, 8, 7], color='black')

However, I have a hard time controlling the color in plotly . How do I get the above result with plotly ? I have tried a kind-of workaround, which gives me two lines with the same color, but not the color I want (which is black):

import numpy as np
import pandas as pd
import plotly.express as px

df = pd.DataFrame({'x': [0, 1, 2, 4], 'y1': [0, 1, 2, 3], 'y2': [10, 9, 8, 7]})
fig = px.line(df, x='x', y=['y1', 'y2'], color=np.ones(len(df))

The result should look something like this:

在此处输入图像描述

I understand that it is normally "bad practice" to use the same color for two lines. However, in this specific case it is not; I want to plot some self-defined boundaries that function as a reference for other data that is to be added to the figure.

EXTRA: These lines should not be included in the legend. However, I want to plot 2D data in between these lines for which I would like to use some color-coding. This color-coding is preferably in the legend/added as a colorbar.

Thank you very much for your help!

Since Plotly documentation does not describe desired output, try avoiding color variable.

For instance:

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp")
fig.show()

Gives this output:

输出

  • plotly express by default assigns color from color sequence for each trace
  • there are two traces in your figure as you have passed a list length 2 of columns to y
  • as simple a way as any is to override assigned color with update_traces()
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.DataFrame({'x': [0, 1, 2, 4], 'y1': [0, 1, 2, 3], 'y2': [10, 9, 8, 7]})
fig = px.line(df, x='x', y=['y1', 'y2']).update_traces(line_color="black", showlegend=False)

fig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM