Home > Software design >  Creating a bar plot in python
Creating a bar plot in python

Time:12-26

I'm working on my school project which asks me to create a bar plot. I'm unable to understand the function, can anyone please help?

def get_barplot(f_dict,title):
    """
    *******  CHANGE 2 (50 points) **********
    Shows and saves the Bar Plot
    """
    #Uncomment and fill the blanks
    freq_df = pd.DataFrame(f_dict._______,columns=['key','value']) #coverts the dictionary as dataframe
    bar_plot = ___.barplot(_________________________)
    bar_plot.set(title=title '_BarPlot',xlabel='Words', ylabel='Count') #Setting title and labels
    plt.xticks(rotation=45) #Rotating the each word beacuse of the length of the words
    plt.show()
    bar_plot.figure.savefig(title '_barplot.png',bbox_inches='tight') #saving the file

This is the code. Can anyone please let me know what should i write in the blanks given? I've spent the last hour trying to understand but I can't

I tried to use different methods but it didnt work.

CodePudding user response:

It is always useful to look at the API documentation when trying to understand the library functions.

Blank 1: In the first line of your code you are trying to create a Pandas data frame from a dictionary. The first argument for pd.DataFrame is the data (see pandas.DataFrame). In this case, the items in your dictionary i.e. f_dict.items(). The columns parameter provides you a clue here as these are "key" and "value" i.e. an item in the dictionary.

Blanks 2 and 3: I assume you are using Seaborn which has a .barplot method (see seaborn.barplot). I also assume that this has been imported with the alias sns. Seaborn's .barplot method takes a data frame as the first argument which in this case would be the data frame you created in the first line of your code i.e. sns.barplot(data=freq_df).

CodePudding user response:

Firstly, you must pass to the dataframe method not just a dictionary, but its items:

freq_df = pd.DataFrame(f_dict.items(),columns=['key','value'])

Next, you need to create a barplot. Pandas has a slightly different method for creating a barplot (.plot.bar()), in your case you use .barplot, which corresponds to the method from the seaborn library. As I understand it, you need to build a barplot for the frequency of values. The following code does this:

bar_plot = sns.barplot(x = 'value', y = freq_df['value'].value_counts(), data = freq_df)

And make sure you import the seaborn library. The abbreviation sns is usually used for it:

import seaborn as sns
  • Related