Python Forum
How to create a plot with line graphs and vertical bars
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create a plot with line graphs and vertical bars
#1
Hi,

I am trying to figure out how to create a graph similar to the following:

[Image: LHt8r.png]

where the x axis has the monthly time data and the y axis represents the Dow Jones average (DJI column on my sample data). I am trying to get the recession months to plot as vertical bars corresponding to the "Regime" column in my sample data.

Here is the code; files are also attached – any help would be greatly appreciated:

import pandas as pd
import plotly.graph_objects as go
import matplotlib as mpl
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import datetime
from datetime import date
import numpy as np

#import data
history = pd.read_csv("sample_data.csv")
history = history.replace(np. nan,'',regex = True)

#filter out recession dates
recession = history.loc[history["Regime"] == "Recession", "Date"]

#plot axvspan for every recession month
for month in recession:
    plt.axvspan(recession, recession + datetime.timedelta(days=1), color="grey", alpha=0.5)   
plt.show()

Attached Files

.csv   sample_data.csv (Size: 1.69 KB / Downloads: 4)
.py   recession_graph.py (Size: 599 bytes / Downloads: 2)
Reply
#2
This example may help.
Reply
#3
See if this NoteBook helps.
Reply
#4
(Feb-23-2023, 06:47 AM)Gribouillis Wrote: This example may help.

Thanks!
Reply
#5
(Feb-25-2023, 08:38 PM)snippsat Wrote: See if this NoteBook helps.

This is exactly what I was trying to do! Thanks so much for your help!
Reply
#6
(Feb-22-2023, 08:14 PM)devansing Wrote: Hi,

I am trying to figure out how to create a graph similar to the following:

[Image: LHt8r.png]

where the x axis has the monthly time data and the y axis represents the Dow Jones average (DJI column on my sample data). I am trying to get the recession months to plot as vertical bars corresponding to the "Regime" column in my sample data.

Here is the code; files are also attached – any help would be greatly appreciated:

import pandas as pd
import plotly.graph_objects as go
import matplotlib as mpl
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import datetime
from datetime import date
import numpy as np

#import data
history = pd.read_csv("sample_data.csv")
history = history.replace(np. nan,'',regex = True)

#filter out recession dates
recession = history.loc[history["Regime"] == "Recession", "Date"]

#plot axvspan for every recession month
for month in recession:
    plt.axvspan(recession, recession + datetime.timedelta(days=1), color="grey", alpha=0.5)   
plt.show()

Hi,

To create a graph similar to the one you provided, you can use Plotly to plot the Dow Jones average (DJI) against monthly time data and use Matplotlib to add vertical bars for the recession months. Here's an example code that you can modify to fit your data:

import pandas as pd
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import datetime

# Load data
history = pd.read_csv("sample_data.csv")
history["Date"] = pd.to_datetime(history["Date"], format="%Y-%m-%d")
history.set_index("Date", inplace=True)

# Filter out recession dates
recession = history.loc[history["Regime"] == "Recession"].index

# Plot Dow Jones average against time
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history["DJI"], mode="lines"))

# Add vertical bars for recession months
for month in recession:
plt.axvspan(month, month + pd.offsets.MonthEnd(0), color="grey", alpha=0.5)

# Update layout
fig.update_layout(
xaxis=dict(title="Date"),
yaxis=dict(title="Dow Jones Average"),
title="Dow Jones Average over Time",
)

# Show plot
fig.show()


In this code, we first load the data and filter out the recession dates. We then use Plotly to plot the Dow Jones average against time. Finally, we use Matplotlib to add vertical bars for the recession months.

Note that we use pd.offsets.MonthEnd(0) to find the end of the current month for each recession date. This ensures that the vertical bars cover the entire month.

Also, if you are using Jupyter Notebook or a similar environment, you may need to add the following code at the beginning of your notebook to display Plotly graphs properly:


import plotly.io as pio
pio.renderers.default = "notebook"


I hope this helps! Let me know if you have any questions.
Reply
#7
(Feb-28-2023, 11:31 AM)get2sid Wrote:
(Feb-22-2023, 08:14 PM)devansing Wrote: Hi,

I am trying to figure out how to create a graph similar to the following:

[Image: LHt8r.png]

where the x axis has the monthly time data and the y axis represents the Dow Jones average (DJI column on my sample data). I am trying to get the recession months to plot as vertical bars corresponding to the "Regime" column in my sample data.

Here is the code; files are also attached – any help would be greatly appreciated:

import pandas as pd
import plotly.graph_objects as go
import matplotlib as mpl
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import datetime
from datetime import date
import numpy as np

#import data
history = pd.read_csv("sample_data.csv")
history = history.replace(np. nan,'',regex = True)

#filter out recession dates
recession = history.loc[history["Regime"] == "Recession", "Date"]

#plot axvspan for every recession month
for month in recession:
    plt.axvspan(recession, recession + datetime.timedelta(days=1), color="grey", alpha=0.5)   
plt.show()

Hi,

To create a graph similar to the one you provided, you can use Plotly to plot the Dow Jones average (DJI) against monthly time data and use Matplotlib to add vertical bars for the recession months. Here's an example code that you can modify to fit your data:

import pandas as pd
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import datetime

# Load data
history = pd.read_csv("sample_data.csv")
history["Date"] = pd.to_datetime(history["Date"], format="%Y-%m-%d")
history.set_index("Date", inplace=True)

# Filter out recession dates
recession = history.loc[history["Regime"] == "Recession"].index

# Plot Dow Jones average against time
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history["DJI"], mode="lines"))

# Add vertical bars for recession months
for month in recession:
plt.axvspan(month, month + pd.offsets.MonthEnd(0), color="grey", alpha=0.5)

# Update layout
fig.update_layout(
xaxis=dict(title="Date"),
yaxis=dict(title="Dow Jones Average"),
title="Dow Jones Average over Time",
)

# Show plot
fig.show()


In this code, we first load the data and filter out the recession dates. We then use Plotly to plot the Dow Jones average against time. Finally, we use Matplotlib to add vertical bars for the recession months.

Note that we use pd.offsets.MonthEnd(0) to find the end of the current month for each recession date. This ensures that the vertical bars cover the entire month.

Also, if you are using Jupyter Notebook or a similar environment, you may need to add the following code at the beginning of your notebook to display Plotly graphs properly:


import plotly.io as pio
pio.renderers.default = "notebook"


I hope this helps! Let me know if you have any questions.

Thanks for this – I typically use Matplotlib and like this approach! However, I ran your code and it produced two separate charts – one for the Dow Jones and the other for the recession bars?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Add multiple vertical rectangles to a chart in plotly? devansing 2 1,234 Jun-20-2023, 07:55 AM
Last Post: snippsat
  Plot Line chart based on the input parthi1705 4 3,477 Feb-28-2023, 12:08 PM
Last Post: get2sid
  Pick a line in a plot with matplotlib Romain 3 5,660 Feb-28-2023, 11:56 AM
Last Post: get2sid
  Help to Plot timeline for intreruption of one line production danut_horincas 2 2,551 Feb-28-2023, 11:48 AM
Last Post: get2sid
  How to plot 2 graphs in one figure? man0s 1 1,377 Apr-25-2022, 09:18 AM
Last Post: Axel_Erfurt
  error bars with dataframe and pandas Hucky 4 4,269 Apr-27-2020, 02:02 AM
Last Post: Hucky
  How to display percentage above the bars in bar graph? WhatsupSmiley 0 8,266 Mar-31-2020, 07:21 PM
Last Post: WhatsupSmiley
  Not able to figure out how to create bar plot on aggregate data - Python darpInd 1 2,308 Mar-30-2020, 11:37 AM
Last Post: jefsummers
  How to create correct scatter plot for PCA? LK91 0 2,122 Dec-11-2019, 07:53 PM
Last Post: LK91
  plotting of graphs mudezda1 2 2,834 Feb-11-2019, 12:44 PM
Last Post: mudezda1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020