0

What I want to do

I want to draw a horizontal line in the graph shown below.

Code and its explanation

I have a dataframe df which has two columns. One is the datetime column which contains datatime.datetime type values and another is the bgl column which contains integer values.

I extract data between 2022/1/31 and 2022/2/6 from df and then store it in the dataframe df_x. df_x is converted into a list type and then used to draw a graph. So I think the unit of the x-axis might be datetime.datetime type.

When I use the ax.text() method, I specified the X position to be datetime.datetime type, which is correctly shown in the graph.

Now I want to draw a horizontal line in the graph, so I specified datetime.datetime type values for both xmin and xmax. When I run the code, however, an error has occurred like below:

builtins.ValueError: xmin must be a single scalar value, but got 2022-01-31 00:00:00

So my question is: How should I specify both xmin and xmax to draw a horizontal line?

My full code:

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

df = pd.DataFrame({"datetime":dt_string,"bgl":valbgl})
df["bgl"] = df["bgl"].astype("int")

df_x = df[(df["datetime"] >= datetime.datetime(2022,1,31,0,0,0))&(df["datetime"] <= datetime.datetime(2022,2,6,23,59,59))]

fig = plt.figure(figsize=(14,5), tight_layout=True)
ax = fig.add_subplot()
ax.set_ylim((50,400))
ax.grid(True)
ax.xaxis.set_major_locator(mdates.DayLocator(bymonthday=None, interval=1, tz=None))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
ax.text(datetime.datetime(2022,1,31,12,0,0),300,"STRING",fontsize=14) 

plt.axhline(xmin=datetime.datetime(2022,1,31,0,0,0),xmax=datetime.datetime(2022,2,6,23,59,59),y=200,color="RED") 

ax.plot(df_x["datetime"].tolist(),df_x["bgl"].tolist())
plt.show()

Output:

my output graph

Environment:

  • Windows 10
  • Python v3.10.2
  • Matplotlib v3.5.1
  • Pandas v1.4.0
Shaido
  • 27,497
  • 23
  • 70
  • 73
kazutaka
  • 39
  • 1
  • 6
  • 1
    Dear richardec, thank you for your correction. – kazutaka Feb 08 '22 at 02:35
  • You're welcome. You say your English isn't great, but I find it pretty good :) –  Feb 08 '22 at 02:36
  • 1
    Does this answer your question? [Plot a horizontal line using matplotlib](https://stackoverflow.com/questions/33382619/plot-a-horizontal-line-using-matplotlib) You can see the anweres here that suggest using `hlines()` instead of `axhline`, it will allow you to specify `xmin` and `xmax` values following the actual data values. – Shaido Feb 08 '22 at 03:11
  • 1
    Dear Shaido, THANK YOU !! I can now successfully draw horizontal line on the graph. – kazutaka Feb 08 '22 at 03:29
  • @kazutaka: No problems, happy to help :) – Shaido Feb 08 '22 at 05:33

0 Answers0