Draw a plot in which the Y-axis text data (not numeric), and X-axis numeric data

后端 未结 3 1770
说谎
说谎 2021-01-29 09:59

I can create a simple columnar diagram in a matplotlib according to the \'simple\' dictionary:

import matplotlib.pyplot as plt
D = {u\'Label1\':26, u\'Label2\'         


        
3条回答
  •  逝去的感伤
    2021-01-29 10:40

    You may use numpy to convert the dictionary to an array with two columns, which can be plotted.

    import matplotlib.pyplot as plt
    import numpy as np
    
    T_OLD = {'10' : 'need1', '11':'need2', '12':'need1', '13':'need2','14':'need1'}
    x = list(zip(*T_OLD.items()))
    # sort array, since dictionary is unsorted
    x = np.array(x)[:,np.argsort(x[0])].T
    # let second column be "True" if "need2", else be "False
    x[:,1] = (x[:,1] == "need2").astype(int)
    
    # plot the two columns of the array
    plt.plot(x[:,0], x[:,1])
    #set the labels accordinly
    plt.gca().set_yticks([0,1])
    plt.gca().set_yticklabels(['need1', 'need2'])
    
    plt.show()
    

    The following would be a version, which is independent on the actual content of the dictionary; only assumption is that the keys can be converted to floats.

    import matplotlib.pyplot as plt
    import numpy as np
    
    T_OLD = {'10': 'run', '11': 'tea', '12': 'mathematics', '13': 'run', '14' :'chemistry'}
    x = np.array(list(zip(*T_OLD.items())))
    u, ind = np.unique(x[1,:], return_inverse=True)
    x[1,:] = ind
    x = x.astype(float)[:,np.argsort(x[0])].T
    
    # plot the two columns of the array
    plt.plot(x[:,0], x[:,1])
    #set the labels accordinly
    plt.gca().set_yticks(range(len(u)))
    plt.gca().set_yticklabels(u)
    
    plt.show()
    

提交回复
热议问题