How to specify values for my x-axis using matplotlib.pyplot?

Asked

Viewed 5,773 times

4

I am unable to specify values for my x-axis, using matplotlib.pyplot.

In some images the chart.xticks(years) solves the problem, but it seems that when the x-axis value set is too small, it uses standard values [0,1,2,...,N]

A case that works: inserir a descrição da imagem aqui

A case that doesn’t work: inserir a descrição da imagem aqui

My code until then:

import matplotlib.pyplot as chart
from matplotlib import lines

   # Settings
    chart.title(file_name)
    chart.xlabel('Years')
    chart.ylabel('Committers/Contributions')
    chart.ylim([0,highest_value + 100])
    chart.xlim(first_year,2017)

    # Values
    committer_line = chart.plot(committers_dict.keys(),committers_dict.values(),'r',label='Committer')
    contribution_line = chart.plot(contributions_dict.keys(),contributions_dict.values(),'b--',label='Contribution')
    years = list(range(first_year,2017))
    chart.xticks(years)

    # Legend
    chart.legend()

    # Show/Save
    chart.savefig(images_path + file_name.replace('.txt','-commiter-contribution.eps'), format='eps')
    chart.show()

1 answer

2


The values of matplotlib are simply in scientific notation. It is possible to turn off the scientific notation but may give rise to other problems (such as having overlaid text). A more definitive solution is to indicate the strings of your Abels (in ticks) as well as positions (and I suggest rotation). A good solution is:

import matplotlib.pyplot as chart
from matplotlib import lines
import random

# dados gerados para esta soluçao
first_year = 2011
x1 = range(first_year,2017+1)
y1 = [random.randint(0,1100) for i in range(len(x1))]
y2 = [random.randint(0,1100) for i in range(len(x1))]
highest_value = max([max(y1),max(y2)])
file_name = 'Titulo'

# Settings
chart.title(file_name)
chart.xlabel('Years')
chart.ylabel('Committers/Contributions')
chart.ylim([0,highest_value + 100])
chart.xlim(first_year,2017)

# Values
committer_line = chart.plot(x1,y1,'r',label='Committer')
contribution_line = chart.plot(x1,y2,'b--',label='Contribution')
years = list(range(first_year,2017))
chart.xticks(years,[str(i) for i in years],rotation=45) # Usa isto para definires as tuas labels

# Legend
chart.legend()

# Show/Save
#chart.savefig(images_path + file_name.replace('.txt','-commiter-contribution.eps'), format='eps')
chart.show()

, which gives rise to this graph:

Mudar as labels dos ticks

To answer your question directly (if you don’t want to use the suggestion above) to turn off the scientific notation you can do:

ax.get_xaxis().get_major_formatter().set_scientific(False)

, in which the ax could be built as follows (among others):

ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)

You’d have to call your own plot from the ax.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.