Force matplotlib show only positive numbers starting at 0 on y-axis

In a loop, I created several subplots using Matplotlib.

I noticed that in some cases the Y-axis (especially when displaying 0) shows some negative numbers on the Y-axis.

Is there a parameter to force the Y-axis to display positive numbers (i.e. from 0 upwards.

And an option to have the Y-axis value indicate either one or no decimal places. (displaying 2 instead of 2.0 or 2.00 (which seems to be done automatically based on the data).

code:

for a in account_list:
    f = plt.figure()
    f.set_figheight(20)
    f.set_figwidth(20)
    f.sharex = True
    f.sharey=True

    left  = 0.125  # the left side of the subplots of the figure
    right = 0.9    # the right side of the subplots of the figure
    bottom = 0.1   # the bottom of the subplots of the figure
    top = 0.9      # the top of the subplots of the figure
    wspace = 0.2   # the amount of width reserved for blank space between subplots
    hspace = .8  # the amount of height reserved for white space between subplots
    subplots_adjust(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace)

    count = 1
    for h in headings:
        sorted_data[sorted_data.account == a].ix[0:,['month_date',h]].plot(ax=f.add_subplot(7,3,count),legend=True,subplots=True,x='month_date',y=h)

        import matplotlib.patches as mpatches
        legend_name = mpatches.Patch(color='none', label=h)
        plt.xlabel("")
        ppl.legend(handles=[legend_name],bbox_to_anchor=(0.,1.2,1.0,.10), loc="center",ncol=2, mode="expand", borderaxespad=0.)
        count = count + 1

      

enter image description here

EDIT

When I set the minimum and maximum for the Y axis using the below, I end up with repeating numbers. For example, where the graph took place on the Y-axis: 1, 1.5, 2, 2.5 it now just has 1, 1, 2, 2, 3, 3, (I want each number to be displayed only once.

Maybe it is because the if statement is not working. I want all plots with a maximum Y-axis value below ten so that their maximum Y-value is set to ten.

#set bottom Y axis limit to 0 and change number format to 1 dec place.
    axis_data = f.gca()

    from matplotlib.ticker import FormatStrFormatter
    axis_data.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))

    #set only integers on Y axis >>>
    import matplotlib.ticker as ticker
    axis_data.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))

    #if y max < 10 make it ten
    ymin,ymax = axis_data.get_ylim()
    print(type(ymax))

    if ymax <10:
        axis_data.set_ylim(bottom=0.,top=ymax)
    else:
        axis_data.set_ylim(bottom=0.)

      

enter image description here

+3


source to share


3 answers


ax.set_ylim

is a method that changes the limits on the y-axis of the subplot. To use this, you must have an instance at your disposal Axes

(the one that is returned plt.subplot

); then you can set the lower limit to 0. Something along these lines should work:

ax = plt.subplot(1, 1, 1)
ax.plot(x, y)
ax.set_ylim(bottom=0.)
plt.show()

      

To change the label format of a label, one convenient way is to use FormatStrFormatter

:

from matplotlib.ticker import FormatStrFormatter
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))

      

EDIT : I have looked at your code; you can get an instance Axes

with a method fig.gca()

and then set ylim and major_formatter as described above.



EDIT2 : The problem in this question can be solved by specifying the locator ticks . The default locator, AutoLocator

which is essentially the MaxNLocator

default. One of the keywords MaxNLocator

is an integer, which specifies only integer values ​​for ticks and is equal by default False

. Thus, to make ticks only accept integer values, you need to define for the y-axis MaxNLocator

with integer=True

. This should work:

from matplotlib.ticker import MaxNLocator
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

      

EDIT3

And if you want to set the upper limit of y to 10, you must explicitly set it to 10:

if ymax < 10:
    axis_data.set_ylim(bottom=0., top=10.)
else:
    axis_data.set_ylim(bottom=0.)

      

+2


source


The range of the axes can be limited to a specific range xlim()

or ylim()

, for example.

ylim([0,2])

      



and the axis ticks can be manually set for any line using xticks()

or yticks()

, for example.

yticks([0,1,2],["0","1","2"])

      

+1


source


Unfortunately, there are many ways to customize ticks. Therefore, it can sometimes become a mess.

Try:

tickpos = [1,2,5]

py.axis(ymin = 0)
py.yticks(tickpos,tickpos)

      

If you don't use tickpos in both arguments and you use two different arrays, the first array tells where the ticks are. The second one says what these labels are. This is useful if you want the label to be a row (let's say it's a bar chart and you want the label to be a category for a given row). It is very dangerous if you have them as numbers, because you may find that you are moving the checkmark, but not the label. So you denote the location y = 4 as say 6. The next would be BAD

py.yticks([1,2,3], [1, 4, -1])  #DO NOT DO THIS

      

You can also set py.axis (ymin = 0, ymax = 4, xmin = 3) or other options, depending on which limits you want to set for free. As a side note, I sometimes set ymax = 4.000001 if I want to be sure there is a check mark at y = 4.

+1


source







All Articles