Plot string values in matplotlib

后端 未结 5 2105
南旧
南旧 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.

提交回复
热议问题