简体   繁体   中英

Python: CSV to Barchart using Matplotlib

I would like to draw a Bar chart from a CSV file which has the following format:

#Number of Occurrences, Occurrences of A, Occurrences of B, Occurrences of C
30,1,3,26
...

I am totally new to Matplotlib and I'm trying to understand how to do it. I wish for the y Axis to have the #Number of Occurences value (30 for the provided example), and three bars; The bar A,B and C with the respective values.

How could I do it?

My Code:

#!/usr/bin python



import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys

def main():

    table  = pd.read_csv(sys.argv[1])

    final = table.tail(1)

    names_list = list(final)
    values     = [ final.values[0][1], final.values[0][2], final.values[0][3] ]

    position = np.arange(len(names_list)) 

    plt.title(sys.argv[1].split('.')[0])

    plt.bar(position,values,align='center')

    plt.yticks(position,names_list)

    plt.show()



if __name__ == '__main__':
    main()

But I get **ValueError: shape mismatch: objects cannot be broadcast to a single shape**

The error is because 'values' has 3 values on it, and position has 4 values on it. So, shape mismatch. There are also other things with x and y axis. Check this code and let me know if it does what you expect:

def main():

    table  = pd.DataFrame([[30, 1, 3, 26]], columns=['Number Oc', 'Oc A', 'Oc B', 'Oc C'])

    final = table.tail(1)

    names_list = list(final)
    values     = [ final.values[0][1], final.values[0][2], final.values[0][3] ]

    position = np.arange(len(names_list)-1)

    plt.title(sys.argv[1].split('.')[0])

    plt.bar(position,values,align='center')

    plt.xticks(position, names_list[1:4])

    plt.show()

ValueError: shape mismatch: objects cannot be broadcast to a single shape


Debug your code:

  1. Watch len(position)
  2. Watch len(values)
  3. Compare len(position) and len(values)
  4. You can find your len(position)!=len(values)
  5. matplotlib.pyplot.bar(x, height) require “The x coordinates of the bars and The height(s) of the bars should have the same length.”

So you should keep the lengths of the two arrays consistent according to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM