How to plot two lists in descending order based on y values?

前端 未结 3 510
甜味超标
甜味超标 2021-01-21 10:12

I have two lists. The first is a list of strings a

[\'Agriculture/Forestry/Fisheries/Veterinary Medicine\',
 \'Architectural and Town Planning\',
 \         


        
相关标签:
3条回答
  • 2021-01-21 10:23

    A simple data rearrangement approach:

    import matplotlib.pyplot as plt
    
    a = [
        'Agriculture/Forestry/Fisheries/Veterinary Medicine',
        'Architectural and Town Planning',
        'Business Administration and Related'
    ]
    
    b = [66667.0, 22283.0, 670091.5]
    
    b, a = zip(*sorted(zip(b, a), reverse=True))  # reverse sort data on 'b'
    
    c = range(len(b))
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.bar(c, b)
    plt.xticks(c, a, rotation=90)
    plt.show()
    

    0 讨论(0)
  • 2021-01-21 10:24

    Use numpy

    • list(zip(list_name, list_count)) zips the two lists into a list of tuples
      • Convert the list of tuples into a np.array with dtypes
    • np.sort sorts by ascending (smallest to largest)
    • [::-1] reverses the array
    • The benefits are, matplotlib easily accepts arrays, and the numpy column can be passed with its name.
    import numpy as np
    import matplotlib.pyplot as plt
    
    text = ['Agriculture/Forestry/Fisheries/Veterinary Medicine', 'Architectural and Town Planning', 'Business Administration and Related']
    
    values = [66667.0, 22283.0, 670091.5]
    
    # get the length of the longest string in text, for the numpy str dtype
    # this is only necessary if make sure the entire string is included in the array
    str_len = max([len(t) for t in text])
    
    # create numpy array with dtypes
    t = np.array(list(zip(text, values)), dtype = [('text', f'S{str_len}'), ('values', int)])
    
    # sort array
    t = np.sort(t, order=['values'])[::-1]
    
    # plot
    plt.bar(x=t['text'], height=t['values'])
    plt.xticks(rotation=90)
    

    0 讨论(0)
  • 2021-01-21 10:36

    Is this what you are trying to do:

    import matplotlib.pyplot as plt
    import pandas as pd
    %matplotlib inline
    
    categories = ['Agriculture/Forestry/Fisheries/Veterinary Medicine',
     'Architectural and Town Planning',
     'Business Administration and Related']
    
    values = [66667.0,22283.0,670091.5]
    
    df = pd.DataFrame(columns=['category', 'value'])
    df = df.append([{"category":a, "value":b} for a, b in zip(categories, values)])
    
    df.sort_values('value', ascending=False)[['category','value']].plot.bar()
    

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