Plot order
I have a pandas framework that has two columns.
I need a plot ordered by the "Count" column.
dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2' :5055 ,'39' :4758 ,'38' :4611 })
pd_df = pd.DataFrame(list(dicti.iteritems()))
pd_df.columns =["Dim","Count"]
plt.figure(figsize=(12,8))
ax = sns.barplot(x="Dim", y= "Count",data=pd_df )
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "
{:,}".format(int(x))))
ax.set(xlabel="Dim", ylabel='Count')
for item in ax.get_xticklabels():
item.set_rotation(90)
for i, v in enumerate(pd_df["Count"].iteritems()):
ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom',
rotation=45)
plt.tight_layout()
Right now the graph is ordered by the "Dim" column, I need to order it by the "Count" column, how can I do that?
+6
source to share
2 answers
You have to sort your data file as desired and flip it over to create a new ascending / descending index. After that, you can display the histogram with the index as x values. Then set the label labels with the Dim column of your data block:
import matplotlib.pylab as plt
import pandas as pd
import seaborn as sns
dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2' :5055 ,'39' :4758 ,'38' :4611 })
pd_df = pd.DataFrame(list(dicti.items()))
pd_df.columns =["Dim","Count"]
print (pd_df)
# sort df by Count column
pd_df = pd_df.sort_values(['Count']).reset_index(drop=True)
print (pd_df)
plt.figure(figsize=(12,8))
# plot barh chart with index as x values
ax = sns.barplot(pd_df.index, pd_df.Count)
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
ax.set(xlabel="Dim", ylabel='Count')
# add proper Dim values as x labels
ax.set_xticklabels(pd_df.Dim)
for item in ax.get_xticklabels(): item.set_rotation(90)
for i, v in enumerate(pd_df["Count"].iteritems()):
ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom', rotation=45)
plt.tight_layout()
plt.show()
+7
source to share