Hey Guys,

This seems like a basic problem with an easy answer but I simply cannot figure it out no matter how much I try.

I am trying to create a line graph based on two lists. For my x-axis, I want my list to be a set of strings.

x_axis_list = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"]
y_axis_list = [5,7,6,8,9]

Any suggestions on how to best graph these items?

Dani AI

Generated

Short answer: there are two practical routes.

  • Treat the string labels as categorical tick labels (plot y against integer positions and assign the labels). This is simplest when the x values are just labels and you want evenly spaced points.
  • Convert the labels to real dates and plot datetimes. This is the right choice when the spacing between points should reflect real time intervals (so July→January spacing is preserved).

As pointed out, manually placing tick labels works; below are compact examples showing both approaches plus a few common troubleshooting tips.

Example — categorical labels (even spacing)

import matplotlib.pyplot as plt

labels = ["Q1 2019", "Q3 2019", "Q1 2020"]
values = [5, 7, 6]

pos = range(len(labels))
fig, ax = plt.subplots()
ax.plot(pos, values, marker='o')
ax.set_xticks(pos)
ax.set_xticklabels(labels, rotation=45, ha='right')
plt.tight_layout()
plt.show()

Example — real dates (proportional spacing and formatting)

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

dates = [datetime(2019, 1, 1), datetime(2019, 7, 1), datetime(2020, 1, 1)]
values = [5, 7, 6]

fig, ax = plt.subplots()
ax.plot(dates, values, marker='o')
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b-%y'))
fig.autofmt_xdate()
plt.show()

Troubleshooting and tips

  • Ensure x and y arrays are the same length; that is the most common source of “missing” points.
  • Rotate labels and use plt.tight_layout() (or fig.autofmt_xdate()) to avoid overlap.
  • If x labels represent dates, convert them to datetimes (or use pandas time-series plotting) so Matplotlib can space and format them properly.
  • Matplotlib also supports categorical plotting directly; see the categorical example and the xticks docs for more options.

References: Matplotlib categorical plotting example and the xticks API are useful starting points: and xticks documentation.

Recommended Answers

All 2 Replies

Member Avatar for Member #682468
x_axis_list = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"]
y_axis_list = [5,7,6,8,9]

In matplotlib you can use xticks()

The first list is where each text piece will be placed, and the second is a tuple of strings.

xticks([1,2,3,4,5], ("Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"))

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.