im trying to create a program that reads a text file and plots the data using matplotlib. however, what i want to do is subdivide the each major y-axis display into 10 smaller segments. ive tried matplotlib.pyplot.yscale but i cant seem to quite get the hang of it. any help is appreciated. below is the code

import matplotlib.pyplot as mpl
import numpy as npy
import os
import sys
import string

def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
    
fileopen = open ('output.txt' , 'r')
filelist = fileopen.readlines()

angle = []
timeset = []

for onefile in filelist:
    if( isFloat(onefile.strip()) == True ):
        angle.append (eval (onefile))

for dt in range (0,len(angle)): #create time steps equal to the number of input angles
    timeset.append (dt * 1)

mpl.plot (timeset , angle , 'r')
mpl.xlabel ('Time (Seconds)')
mpl.ylabel ('Angle (Degrees)')
mpl.yscale ('linear' , ([range (0,10)]))
mpl.show ()

Hi iwanttolearnc,

I would use the MultipleLocator class. So, what you would do is in your code add the following:

from matplotlib.ticker import MultipleLocator

#sets the minor ticks to be at multiples of 1 along the yaxis
#change the intervals to whatever suits you
minorLocator = MultipleLocator(1)

mpl.yaxis.set_minor_locator(minorLocator)

Let me know if this works for you

Just refactored......

import matplotlib.pyplot as mpl
import numpy as npy #  Redundant imports
import os           #
import sys          #
import string       #

def isFloat(flt):
    try:
        float(flt)
        return True
    except ValueError:
        return False
    
fileopen = open ('output.txt' , 'r')
filelist = fileopen.readlines()

angle = []
timeset = []

for onefile in filelist:
    if( isFloat(onefile.strip())):
        angle.append (eval (onefile))

for dt in range (0,len(angle)): #create time steps equal to the number of input angles
    timeset.append (dt * 1) # why dt *1 ?? ,, just dt i think

mpl.plot (timeset , angle , 'r')
mpl.xlabel ('Time (Seconds)')
mpl.ylabel ('Angle (Degrees)')
mpl.yscale ('linear' , ([range (0,10)]))
mpl.show ()

Happy coding

thank you for answering! ive performed both your suggestions but it still does not seem to work. below is the code sirs.

import matplotlib.pyplot as mpl
from matplotlib.ticker import MultipleLocator

def getmode(li):
    li.sort()
    numbers = {}
    for x in li:
        num = li.count(x)
        numbers[x] = num
    highest = max(numbers.values())
    n = []
    for m in numbers.keys():
        if numbers[m] == highest:
            n.append(m)
    return n

def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
    
fileopen = open ('output.txt' , 'r')
filelist = fileopen.readlines()

angle = []
timeset = []

for onefile in filelist:
    if( isFloat(onefile.strip()) == True ):
        angle.append (eval (onefile))

for dt in range (0,len(angle)): #create time steps equal to the number of input angles
    timeset.append (dt)

minorlocator = MultipleLocator(1)
mpl.yaxis.set_minor_locator(minorLocator)

mpl.plot (timeset , angle , 'r' , label = 'Filter\nOutput')
mpl.xlabel ('Time $(Seconds)$')
mpl.ylabel ('Angle $(Degrees)$')
mpl.legend(loc=0)
mpl.show ()
mpl.close()
##print getmode(angle)[1]

the error that pops up is

AttributeError: 'module' object has no attribute 'yaxis'

Check this out

import matplotlib.pyplot as mpl
print(dir(mpl))

##output
['Annotation', 'Arrow', 'Artist', 'AutoLocator', 'Axes', 'Button', 'Circle', 'Figure', 'FigureCanvasBase', 'FixedFormatter', 'FixedLocator', 'FormatStrFormatter', 'Formatter', 'FuncFormatter', 'IndexLocator', 'Line2D', 'LinearLocator', 'Locator', 'LogFormatter', 'LogFormatterExponent', 'LogFormatterMathtext', 'LogLocator', 'MaxNLocator', 'MultipleLocator', 'Normalize', 'NullFormatter', 'NullLocator', 'PolarAxes', 'Polygon', 'Rectangle', 'ScalarFormatter', 'Slider', 'SubplotTool', 'Text', 'TickHelper', 'Widget', '__builtins__', '__doc__', '__docstring_addendum', '__file__', '__name__', '__package__', '_backend_selection', '_imread', '_imsave', '_interactive_bk', '_pylab_helpers', '_setp', '_x', 'acorr', 'annotate', 'arrow', 'autumn', 'axes', 'axhline', 'axhspan', 'axis', 'axvline', 'axvspan', 'bar', 'barbs', 'barh', 'bone', 'box', 'boxplot', 'broken_barh', 'cla', 'clabel', 'clf', 'clim', 'close', 'cm', 'cohere', 'colorbar', 'colormaps', 'colors', 'connect', 'contour', 'contourf', 'cool', 'copper', 'csd', 'dedent', 'delaxes', 'disconnect', 'draw', 'draw_if_interactive', 'errorbar', 'figaspect', 'figimage', 'figlegend', 'fignum_exists', 'figtext', 'figure', 'fill', 'fill_between', 'fill_betweenx', 'findobj', 'flag', 'gca', 'gcf', 'gci', 'get', 'get_backend', 'get_cmap', 'get_current_fig_manager', 'get_fignums', 'get_plot_commands', 'get_scale_docs', 'get_scale_names', 'getp', 'ginput', 'gray', 'grid', 'hexbin', 'hist', 'hlines', 'hold', 'hot', 'hsv', 'imread', 'imsave', 'imshow', 'interactive', 'ioff', 'ion', 'is_numlike', 'is_string_like', 'ishold', 'isinteractive', 'jet', 'legend', 'loglog', 'matplotlib', 'matshow', 'minorticks_off', 'minorticks_on', 'mlab', 'new_figure_manager', 'normalize', 'np', 'over', 'pcolor', 'pcolormesh', 'pie', 'pink', 'plot', 'plot_date', 'plotfile', 'plotting', 'polar', 'prism', 'psd', 'pylab_setup', 'quiver', 'quiverkey', 'rc', 'rcParams', 'rcParamsDefault', 'rcdefaults', 'register_cmap', 'rgrids', 'savefig', 'scatter', 'sci', 'semilogx', 'semilogy', 'set_cmap', 'setp', 'show', 'silent_list', 'specgram', 'spectral', 'spring', 'spy', 'stem', 'step', 'subplot', 'subplot_tool', 'subplots_adjust', 'summer', 'suptitle', 'switch_backend', 'sys', 'table', 'text', 'thetagrids', 'title', 'twinx', 'twiny', 'vlines', 'waitforbuttonpress', 'winter', 'xcorr', 'xlabel', 'xlim', 'xscale', 'xticks', 'ylabel', 'ylim', 'yscale', 'yticks']

And there is not yaxis
This is the methods inside the module you imported.

Ah yes, sorry you first need to create a figure instance which will contain all the plot elements. So your code would now be:

import matplotlib.pyplot as mpl
from matplotlib.ticker import MultipleLocator

def getmode(li):
    li.sort()
    numbers = {}
    for x in li:
        num = li.count(x)
        numbers[x] = num
    highest = max(numbers.values())
    n = []
    for m in numbers.keys():
        if numbers[m] == highest:
        n.append(m)
    return n

def isFloat(string):
    try:
        float(string)
        return True

    except ValueError:
        return False

fileopen = open ('output.txt' , 'r')

filelist = fileopen.readlines()

angle = []
timeset = []

for onefile in filelist:
    if( isFloat(onefile.strip()) == True ):
        angle.append (eval (onefile))

for dt in range (0,len(angle)): #create time steps equal to the number of input angles
    timeset.append (dt)

#create a figure instance which will contain all plot elements
fig = mpl.figure()

#add a subplot in the figure
#this means we can use this to set all the plot elements
ax = fig.add_subplot(111)

minorlocator = MultipleLocator(1)
ax.yaxis.set_minor_locator(minorLocator)

ax.plot (timeset , angle , 'r' , label = 'Filter\nOutput')
ax.set_xlabel ('Time $(Seconds)$')
ax.set_ylabel ('Angle $(Degrees)$')
ax.legend(loc=0)
mpl.show ()
mpl.close()
##print getmode(angle)[1]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.