I am trying to plot multiple line charts in a single line chart. And also want give different color to different lines. Add legend to understand which color represents which lines. I tried two different codes, but none of the works.
Code 1:
st.line_chart(stock, x="ds", y="y", color="#0514C0")
st.line_chart(prediction, x="ds", y="y", color="#4CC005")
Code 2:
fig = px.line(stock, x="ds", y="y")
fig = px.line(prediction, x="ds", y="y")
# Plot!
st.plotly_chart(fig, use_container_width=True)
Hi @Sanniddha
Is this what you mean:
import streamlit as st
import pandas as pd
import plotly.express as px
stock = pd.DataFrame({
'ds': ['2024-01-01', '2024-01-02', '2024-01-03'],
'y': [10, 15, 12]
})
prediction = pd.DataFrame({
'ds': ['2024-01-01', '2024-01-02', '2024-01-03'],
'y': [12, 14, 16]
})
fig = px.line(stock, x="ds", y="y", color_discrete_sequence=["#0514C0"], labels={'y': 'Stock'})
fig.add_scatter(x=prediction['ds'], y=prediction['y'], mode='lines', name='Prediction', line=dict(color='#4CC005'))
fig.update_layout(title='Stock vs Prediction', xaxis_title='Date', yaxis_title='Value')
st.plotly_chart(fig, use_container_width=True)
Best,
Charly
Hi @Charly_Wargnier
I want to plot like this:
But this should be interactive, like your graph
So to display two colors on the same chart, you might want to try it this way, although there are different methods:
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
dates = pd.date_range(start='2012-01-01', end='2024-01-01', freq='M')
actual_prices = np.abs(np.random.normal(loc=0.0, scale=10, size=len(dates))).cumsum() + 50
split_index = len(dates) // 2
plt.figure(figsize=(15, 8))
plt.plot(dates[:split_index], actual_prices[:split_index], color='blue', label='Price (First Half)')
plt.plot(dates[split_index:], actual_prices[split_index:], color='red', label='Price (Second Half)')
plt.title('Price Trend Over Time with Color Transition')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
st.pyplot(plt)
Here’s the output:
Would that work for you?
Best,
Charly
If you want to have it in Plotly, try this code:
import streamlit as st
import plotly.graph_objs as go
import pandas as pd
import numpy as np
dates = pd.date_range(start='2012-01-01', end='2024-01-01', freq='M')
actual_prices = np.abs(np.random.normal(loc=0.0, scale=10, size=len(dates))).cumsum() + 50
split_index = len(dates) // 2
trace1 = go.Scatter(x=dates[:split_index], y=actual_prices[:split_index], mode='lines', name='Price (First Half)', line=dict(color='blue'))
trace2 = go.Scatter(x=dates[split_index - 1:], y=actual_prices[split_index - 1:], mode='lines', name='Price (Second Half)', line=dict(color='red'))
data = [trace1, trace2]
layout = go.Layout(title='Price Trend Over Time with Color Transition',
xaxis=dict(title='Date'),
yaxis=dict(title='Price'),
hovermode='closest')
fig = go.Figure(data=data, layout=layout)
st.plotly_chart(fig)
Hi @Charly_Wargnier
The first code doesn’t works well.
The second code plot only one line, not the both line
I have a dataframe name Stock having two columns Date and Price.
Another dataframe name Prediction having two columns Date and Price.
I want to plot Date vs Price chart (line plot) for both the dataframe in a single graph. And distinguish the two lines with different color.
X axis label must be Date and Y axis label must be Price.
Also add add legend in the plot to show color represents which line.
Hi @Sanniddha,
I provided my example to show you how to create a line in your chart with two colors. You can use this code snippet in your project for your specific use case.
Wishing you the best of luck! Please keep us updated on your progress.
Best,
Charly
Hi @Charly_Wargnier
This is the code I use for my project. I take this code snippet from your code:
trace1 = go.Scatter(x=stock['ds'], y=stock['y'], mode='lines', name='Actual Price', line=dict(color='blue'))
trace2 = go.Scatter(x=prediction['ds'], y=prediction['y'], mode='lines', name='Predicted Price', line=dict(color='red'))
data = [trace1, trace2]
layout = go.Layout(title='Actual Price vs Predicted Price',
xaxis=dict(title='Date'),
yaxis=dict(title='Price'),
hovermode='closest')
fig = go.Figure(data=data, layout=layout)
st.plotly_chart(fig)
This generate the below plot
You can notice that this code plots only one line. It doesn’t plot Actual Price plot (color blue)
You’d need this:
import streamlit as st
import plotly.graph_objs as go
import pandas as pd
import numpy as np
date_range = pd.date_range(start="2023-01-01", end="2023-12-31", freq='M')
data = date_range.month + np.random.normal(0, 1, size=len(date_range))
data_green_line = np.linspace(start=20, stop=10, num=len(date_range)) + np.random.normal(0, 1, size=len(date_range))
split_index = len(data) // 2
trace_blue = go.Scatter(x=date_range[:split_index], y=data[:split_index], mode='lines', name='Blue Part', line=dict(color='blue'))
trace_red = go.Scatter(x=date_range[split_index-1:], y=data[split_index-1:], mode='lines', name='Red Part', line=dict(color='red'))
trace_green = go.Scatter(x=date_range, y=data_green_line, mode='lines', name='Green Line', line=dict(color='green'))
data_combined = [trace_blue, trace_red, trace_green]
layout = go.Layout(title='Combined Chart with Blue-Red Transition and Green Line',
xaxis=dict(title='Date'),
yaxis=dict(title='Data Value'),
hovermode='closest')
fig_combined = go.Figure(data=data_combined, layout=layout)
st.plotly_chart(fig_combined)
Would that work?
Hi @Charly_Wargnier
How can I do this without this code snippet since my dataframe is already created:
date_range = pd.date_range(start="2023-01-01", end="2023-12-31", freq='M')
data = date_range.month + np.random.normal(0, 1, size=len(date_range))
data_green_line = np.linspace(start=20, stop=10, num=len(date_range)) + np.random.normal(0, 1, size=len(date_range))
split_index = len(data) // 2
I have a dataframe name Stock having two columns Date and Price .
Another dataframe name Prediction having two columns Date and Price .
You’ll need to replace the dummy data with referenced elements from your dataframe.
Charly
@Charly_Wargnier Just wanted to thank you for answering these questions because I feel like you aren’t getting enough appreciation and there’s people like me that lurk and find all this very useful.
1 Like
Thank you for your thoughtful words, @Dimitri_S – you’ve brightened my day!
Happy Streamlitin’!
Charly