Reputation: 672
I have a csv file whose data looks like this :
A B C D E
feature1 0.6388 0.581 0.612 0.571 0.5758
feature2 0.6218 0.537 0.624 0.535 0.6235
feature3 0.5639 0.404 0.56 0.497 0.569
feature4 0.6695 0.622 0.656 0.542 0.6337
feature5 0.6252 0.532 0.625 0.523 0.6235
feature6 0.6712 0.584 0.641 0.52 0.632
where I have 6 features of 5 classes. I want to plot this as a bar chart ( x axis will have the features and y axis values from 0 to 1, and the bars
would be of class A,B...). How do I do this without redundant coding?
Upvotes: 2
Views: 515
Reputation: 153460
I would use pandas....
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
csvfile = StringIO("""
A B C D E
feature1 0.6388 0.581 0.612 0.571 0.5758
feature2 0.6218 0.537 0.624 0.535 0.6235
feature3 0.5639 0.404 0.56 0.497 0.569
feature4 0.6695 0.622 0.656 0.542 0.6337
feature5 0.6252 0.532 0.625 0.523 0.6235
feature6 0.6712 0.584 0.641 0.52 0.632""")
df=pd.read_csv(csvfile, sep='\s\s+', index_col=0)
ax = df.plot.bar()
ax.set_ylim(0,1)
ax.legend(ncol=5,loc='upper center')
plt.show()
Output:
Just getting fancy for the fun of it.
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
csvfile = StringIO("""
A B C D E
feature1 0.6388 0.581 0.612 0.571 0.5758
feature2 0.6218 0.537 0.624 0.535 0.6235
feature3 0.5639 0.404 0.56 0.497 0.569
feature4 0.6695 0.622 0.656 0.542 0.6337
feature5 0.6252 0.532 0.625 0.523 0.6235
feature6 0.6712 0.584 0.641 0.52 0.632""")
df=pd.read_csv(csvfile, sep='\s\s+', index_col=0)
ax = df.plot.bar(zorder=2)
ax.set_ylim(0,1)
ax.legend(ncol=5,loc='upper center')
ax.grid(axis='y')
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
Output:
Upvotes: 4
Reputation: 150735
Do you mean something like
import pandas as pd
df = pd.read_csv('file.csv')
df.plot.bar()
Output:
Upvotes: 4