Search code examples
pythonmatplotlibplotaxis-labels

matplotlib x axis values


I have a problem with graphical representation of a plot in matplotlib. There are two issues:

  1. I do not count y for every x value. For example list of y: [1.0, 3.5, 3.3, 1.1, 2.4] does not correspond to x: [1, 2, 3, 4, 5], but to [2, 6, 10, 14, 18] (the spaces are always regular).

I have solved this problem, but in very unellegnt way:

plt.xticks(list(range(len(my_list))), list(range(bound[0], bound[1] + 1, delta)))

The result seems to be quite good:

Result of xtick above

  1. The bigger problem occurs when when the bounds are wider. Example: Unreadable

The bounds are from 2 to 1000 with delta 10. x axis values are [2, 12, 22, 32, ...] but it is completely unreadable

So... I have tried a lot to create something better. I ended with obscure and dingy code:

    n_x_axis = 10 #number of values on axis
    x_axis_val = list(range(bound[0], bound[1]+1, delta))
    a = len(my_list)
    b = int(((bound[1]-bound[0] + 1)/delta)//n_x_axis)
    for i in range(0, a, b):
        if i + b < a:
            for j in range(b):
                if j != 0:
                    x_axis_val[i+j] = None
        else:
            for x in range(i, a):
                if x != a-1:
                    x_axis_val[x] = None

    plt.plot(my_list)
    plt.title("my_list")
    plt.xticks(list(range(len(my_list))), x_axis_val)

Here are the result: bound = (2, 10000) delta = 10

enter image description here

I'm sure there is a better way to solve my problem. Maybe there exist some proper function to this ... Despite being so extensive my solution still have disadvantages, for example the points on x axis are to dense.

How can I improve this solution? Thank you in advance.


Solution

  • You can just define the x-values for the corresponding y-values and then plot with

    plt.plot(x, y)
    

    This way, you don't need to mess with any ticks; matplotlib will do this on its own. You can get a list of x-values with a step of 4 for example with

    np.arange(0, 1000, 4)
    

    Docs: