Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Plotting a bar graph in Python files given can be found here: http://www.cse.msu

ID: 3825925 • Letter: P

Question

Plotting a bar graph in Python

files given can be found here: http://www.cse.msu.edu/~cse231/Online/Labs/Lab15/

Bar Graph

We provide a comma-separated-value file, STC_2014_STC005.csv, of tax data from the US Census Bureau: http://www.census.gov/govs/statetax/

We are interested in three columns: state name (at index 2), Total Taxes (at index 3), and Sales and Gross Receipts Taxes (at index 5). There are some header lines to ignore, but the data columns are clean (no missing or weird characters). For each state (i.e. each row) calculate the percent of Total Taxes that are Sales and Gross Receipts Taxes, i.e. values at index 5 over values at index 3. Note that the states are already in alphabetical order (hint: that should guide your choice of data structure).

Write a program that reads that csv file and plots these values as a bar graph with states on the x-axis and percent on the y-axis. Your task is to make a bar graph that looks like this:

To guide you through creating the bar graph we have provided a file bar_demo.py . The demo illustrates how to make a simple bar graph. Run it. There are a number of commented out lines that you will find helpful to make a bar graph look like the one above. Experiment with those lines with the bar_demo.py program and then use what you learn to create the plot above.

demo stubs to edit:

Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Idaho Illinois indiana Iowa Kansa Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota ssissippi Missouri Montana Nebraska Nevada New Hampshire New Jersey New Mexico New York North Carolina North Dakota Ohio Oklahoma Pennsylva Rhode Island South Carolina South Dakota Tennessee Texas Utah Vermont Virginia Washington West Virginia Wisconsin Wyoming Ratio

Explanation / Answer

import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt('data.csv', delimiter=',', skiprows = 1, usecols = range(1,8))
data = data.transpose()
xt = np.loadtxt('data.csv', dtype='str', delimiter=',', skiprows = 1, usecols = (0,))
the rest is plotting bar charts as you did:
width = 0.65
ind = np.arange(11) + 0.75
fig, ax = plt.subplots(1,1)
p0 = ax.bar(ind, data[0], width, color = 'cyan')
p1 = ax.bar(ind, data[1], width, bottom = data[0], color = 'violet')
p2 = ax.bar(ind, data[2], width, bottom = data[0] + data[1], color = 'g')
p3 = ax.bar(ind, data[3], width, bottom = data[0] + data[1] + data[2], color = 'r')
ax.set_ylabel('kWh')
ax.set_xlabel('month')
ax.set_xticks (ind + width/2.)
ax.set_xticklabels( xt, rotation = 80 )
fig.legend( (p0[0], p1[0], p2[0], p3[0]), ('kitchen', 'laundry', 'aircon&heater', 'other') )
fig.tight_layout()
fig.show()