Search code examples
pythonlistmatplotlibvariablesfigsize

matplotlib missing plotted x-values in python


I have search multiple posts with unclear solutions that may or may not be relevant and tried it nevertheless but unable to do so.

My current plot does plot out the figure but it does not show all the values of the year and I want it to be an integer.

My matplotlib code is:

import matplotlib.pyplot as plt

year, value = 0, 0.0

year = [1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014, 2015, 2016]
value = [26242.5,27906.7,29192.7,30407.5,1564.9,2313.5,2989.4,3668.6,22082.6,29964.2,30481.6,35981.7,39597.6,38659.6, 34325.9,6913.5,35780.6,39111.5,37116.5,35385.5]


plt.plot(year, value)
plt.title('A - Value of apples vs Year')
plt.xlabel('Year')
plt.ylabel('Value of apples')
plt.grid(True)
plt.show()

The current plot created is shown below: enter image description here


Solution

  • You can specify your years list as the xticks you are expecting by passing them to plt.xticks docs. I took the liberty of rotating the text as well with rotation=45, otherwise the tick labels overlap.

    Though it isn't part of your question, I will note that the line year, value = 0, 0.0 is almost certianly not doing what you are expecting. It looks like you are wanting to initialize the type (int and float) of each of the lists which will be referenced by the year and value variables, but this isn't necessary or possible. The reassignment to the two lists just overwrites your original assignment. If I'm misunderstanding your intent go ahead and correct me however.

    import matplotlib.pyplot as plt
    
    #year, value = 0, 0.0 -> this line is not doing anything
    
    year = [1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014, 2015, 2016]
    value = [26242.5,27906.7,29192.7,30407.5,1564.9,2313.5,2989.4,3668.6,22082.6,29964.2,30481.6,35981.7,39597.6,38659.6, 34325.9,6913.5,35780.6,39111.5,37116.5,35385.5]
    
    
    plt.plot(year, value)
    ####
    plt.xticks(year, rotation=45)
    ####
    plt.title('A - Value of apples vs Year')
    plt.xlabel('Year')
    plt.ylabel('Value of apples')
    plt.grid(True)
    plt.show()
    

    Your figure plotted with the above changes:

    fixedfig