How to find x and y coordinates in a matplotlib plot?

Screen Link:
https://app.dataquest.io/m/526/storytelling-data-visualization/6/title-and-subtitle

Above image shows a graph with four plots highlighting the 3-5 months span. In the exercise they had given x and y coordinates, so, I just have to place the texts as shown in the above image.
But if I want to create a plot for some other data how can I find these coordinates? Please let me know if anyone has idea about this.

Thank you,
Jayadev

1 Like

In the code, if you comment out the following two lines -

ax.set_yticklabels([])
ax.set_xticklabels([])

and then plot the figures, you will get the following chart -

You can see the axis tick marks now.

And if you check the documentation for the text() function, it states -

x, y float

The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

So, when you use text(), the first two parameters are the origin position of your text. And those x and y values are obtained based on your chart itself. For example, for Jan - Mar above you can see the corresponding location -

ax1.text(1.1, -300, 'Jan - Mar', color='#b00b1e',
         weight='bold', rotation=3)

1.1 is the x-coordinate and -300 is the y-coordinate for the text’s location which you can estimate from the tick marks and estimating a bit.

So, you just have to look at (or get an idea of) the x and y coordinates of where you want to place your text from your chart, and then add it so. You can then experiment to find out the best position for the text too.

Matplotlib does offer some more interactive options that you can look into, but they might not work for the Dataquest terminal. They can work when using Jupyter Notebooks probably. But that’s not really required to focus on too much for the time being as per me.

Hi @jayadev, you can use ax.get_xticks() and ax.get_yticks() to find the x- and y-coordinates in any matplotlib graph.

In [1]: import matplotlib.pyplot as plt

In [2]: fig, ax = plt.subplots()

In [3]: ax.get_xticks()
Out[3]: array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])

In [4]: ax.get_yticks()
Out[4]: array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])

These two methods are especially useful when you’re working with time series data, where the coordinates are different under the hood than the time labels.

2 Likes