Plot string values in matplotlib

后端 未结 5 2097
南旧
南旧 2020-12-06 02:17

I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using plot function expects a nu

相关标签:
5条回答
  • 2020-12-06 02:53

    I couldn't find a convenient way to accomplish that, so I resorted to this little helper function.

    import matplotlib.pyplot as p
    def plot_classes(x, y, plotfun=p.scatter, **kwargs):
        from itertools import count
        import numpy as np
        classes = sorted(set(x))
        class_dict = dict(zip(classes, count()))
        class_map = lambda x: class_dict[x]
        plotfun(map(class_map, x), y, **kwargs)
        p.xticks(np.arange(len(classes)), classes)
    

    Then, calling plot_classes(data["class"], data["y"], marker="+") should work as expected.

    0 讨论(0)
  • 2020-12-06 02:58

    Here's one way which i know works, though i would think creating custom symbols is a more natural way accomplish this.

    from matplotlib import pyplot as PLT
    
    # make up some data for this example
    t = range(8)
    s = 7 * t + 5
    # make up some data labels which we want to appear in place of the symbols
    x = 8 * "dp".split()
    y = map(str, range(8))
    data_labels = [ i+j for i, j in zip(x, y)]
    fig = PLT.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(t, s, "o", mfc="#FFFFFF")     # set the symbol color so they are invisible
    for a, b, c in zip(t, s, data_labels) :
        ax1.text(a, b, c, color="green")
    
    PLT.show()
    

    So this puts "dp1", "dp2",... in place of each of the original data symbols--in essence creating custom "text symbols" though again i have to believe there's a more direct way to do this in matplotlib (without using Artists).

    0 讨论(0)
  • 2020-12-06 03:09

    You should try xticks

    import pylab
    
    names = ['anne','barbara','cathy']
    counts = [3230,2002,5456]
    
    pylab.figure(1)
    x = range(3)
    pylab.xticks(x, names)
    pylab.plot(x,counts,"g")
    
    pylab.show()
    
    0 讨论(0)
  • 2020-12-06 03:13

    From matplotlib 2.1 on you can use strings in plotting functions.

    import matplotlib.pyplot as plt
    x = ["Apple", "Banana", "Cherry"]
    y = [5,2,3]
    
    plt.plot(x, y)
    
    plt.show()
    

    Note that in order to preserve the order of the input strings on the plot you need to use matplotlib >=2.2.

    0 讨论(0)
  • 2020-12-06 03:13

    Why not just make the x value some auto-incrementing number and then change the label?

    --jed

    0 讨论(0)
提交回复
热议问题