1

I'm trying to plot some data into a chart, I'd like for the 'Months' axis to have 'January', 'Feburuary' etc. instead of integers. However if I enter text for this parameter, I get the following error:

NameError: name 'Months' is not defined

Here's my code:

import matplotlib.pyplot as plt

Months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
position = [0, 100, 200, 300, 2,2,2,2,2,2,2,2]

plt.plot(Months, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')

Is there a way of putting static text in here instead of integers?

2 Answers 2

3

Just need to write strings in your list instead of integers:

Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

You can also add the following line to display it in a more user-friendly way.

plt.xticks(rotation=90)
Sign up to request clarification or add additional context in comments.

2 Comments

That's embarrassing that I missed that lmao, thank you so much man!! Got any other cool functions to make the chart look nicer and clearer?
Uhm .. actually, you can do more or less anything you'd like... Enlarge the ticks, the labels, add a nice descriptive title... Maybe you can try to add a grid (alpha is the transparancy of the grid: plt.grid(alpha=0.2)
1

You can use the datetime module:

import matplotlib.pyplot as plt
from datetime import datetime

Months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
position = [0, 100, 200, 300, 2,2,2,2,2,2,2,2]

Months = [datetime.strptime(str(n), "%m").strftime("%B") for n in Months]

plt.plot(Months, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')

plt.show()

Output:

enter image description here


If you want the months to be abbreviated, use the format %b instead of %B:

import matplotlib.pyplot as plt
from datetime import datetime

Months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
position = [0, 100, 200, 300, 2,2,2,2,2,2,2,2]

Months = [datetime.strptime(str(n), "%m").strftime("%B") for n in Months]

plt.plot(Months, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')

plt.show()

Output:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.