-1

This might be a simple task but I am new to plotting in python and is struggling to convert logic into code. I have 3 columns like below that consists of Countries, Quantities and Revenues:

Country Quantities Revenues
United Kingdom 2915836 8125479.97
EIRE 87390 253026.10
Netherlands 127083 245279.99
Germany 72068 202050.01
France 68439 184024.28
Australia 52611 122974.01
Spain 18947 56444.29
Switzerland 18769 50671.57
Belgium 12068 34926.92
Norway 10965 32184.10
Japan 14207 31914.79
Portugal 10430 30247.57
Sweden 10720 24456.55

All I want to do is creating a side by side bars for each country which would represent the revenue and quantity for each region.

So far, i have came across performing this:

sns.catplot(kind = 'bar', data = dj, y = 'Quantities,Revenues', x = 'Country', hue = 'Details')
plt.show()

But this cannot interpret the input "Country".

I hope I am making sense.

  • Well the error should have been not interpreting "Quantities,Revenues" i believe. Anyway, what about `df.set_index("Country").plot.bar()`? or if you want separate y-axes for Quantities and Revenues, `df.set_index("Country").plot.bar(secondary_y="Revenues")`? – Mustafa Aydın Dec 26 '22 at 11:19
  • I set the Country as the index because that (whatever is in the index) is what goes to the x-axis values. – Mustafa Aydın Dec 26 '22 at 11:19
  • Noting that these use the embedded plotting functionality of pandas with the `.plot` accessor, which uses matplotlib under the hood. – Mustafa Aydın Dec 26 '22 at 11:20
  • For the sake of completeness, more granular control in vanilla matplotlib and styling are covered in answers to this question: https://stackoverflow.com/q/14270391 – Lodinn Dec 26 '22 at 12:06

2 Answers2

2

With , you can simply use pandas.DataFrame.plot.bar :

dj.plot.bar(x="Country", figsize=(10, 5))

#dj[dj["Country"].ne("United Kingdom")].plot.bar(x="Country", figsize=(10, 5)) #to exclude UK

With , you can use seaborn.barplot after pandas.DataFrame.melting the original df.

fig, ax = plt.subplots(figsize=(10, 5))
ax.tick_params(axis='x', rotation=90)
dj_m = dj.melt(id_vars="Country", value_name="Values", var_name="Variables")
sns.barplot(data=dj_m, x='Country', y="Values", hue="Variables", ax=ax)

# Output :

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30
1

pandas already has a built-in plotting function: .plot and you can choose which type by specifying it like; .bar(), .scatter() or using kind= and then the type; kind='bar' or kind='scatter'. So, in this situation you will use a bar.

import matplotlib.pyplot as plt # import this to show the plot

df.plot.bar(x="Country", **kwargs) # plot the bars

plt.show() # show it
Pythoneer
  • 319
  • 1
  • 16