Search code examples
pythonmatplotlibaxis-labels

How to set the axis scale and ticklabels using matplotlib object oriented API


I would need some help with plotting in Matplotlib.pyplot under Python2.7!

I want to generate a plot with the following x-axis:

x-axis as it should be

I got so far by using myaxis.set_xticks([0,0.5,1,2,4,6,8]) and it looks good, but if I want to create **an logarithmic x-axis* **, then my axis labels look like this!

wrong x-axis labels

What can I do to have both a log-scaled x-axis and integer formated labels (not logarithmic values as labels either!). Please read the note regarding to the log-scale!!!

While browsing Stackoverflow I found the following similar question, but nothing of the suggestions worked for me and I do not know what I did wrong.

Matplotlib: show labels for minor ticks also

Thanks!

Note: This plot is called Madau-Plot (see:adsabs[dot]harvard[dot]edu Madau (1998) DOI=10.1086/305523). It is common to plot it log-scales and show the z=0.0 value although the axis is log-scaled axis and log10(0)=Error. I definitely want to point out here that this is common use in my field but should not be applied one to one to any other plots. So actually the plot is made with a trick! You plot (1+z) [1,1.5,2,3,5,7,9]] and then translate the x-axis to the pure z-values 0.0 < z 8.0! So what I need to find is how to set xticks to the "translated" values ([0,0.5,1,2,4,6,8])


Solution

  • What if you plotted your datapoint corresponding to x=0 somewhere else, like at x=0.25, then relabel it. For example,

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    
    plot_vals = [0.25, 0.5, 1, 2, 4, 6, 8]
    label_vals = [0, 0.5, 1, 2, 4, 6, 8]
    
    ax.plot(plot_vals, plot_vals, 'k-o')
    
    ax.set_xscale('log')
    ax.set_xticks(plot_vals) 
    ax.set_xticklabels(label_vals) # relabeling the ticklabels
    

    This yields what I think is what you want.

    enter image description here

    You can turn off minor ticks by doing something like:

    ax.tick_params(axis='x', which='minor', bottom='off', top='off')
    

    Edit: Given the edit to the op, this can be done easily by:

    import matplotlib.pyplot as plt
    
    
    original_values = [0, 0.5, 1, 2, 4, 6, 8]
    
    # if using numpy:
    # import numpy as np
    # plot_values = np.array(original_values) + 1
    
    # if using pure python
    plot_values = [i + 1 for i in original_values]
    
    fig, ax = plt.subplots()
    ax.plot(plot_values, plot_values, 'k-o') #substitute actual plotting here
    ax.set_xscale('log')
    ax.set_xticks(plot_values)
    ax.set_xticklabels(original_values)
    

    which yields:

    enter image description here