- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort bars in increasing order in a bar chart in matplotlib?
To sort bars in increasing order in a bar chart in matplotlib, we can take the following steps −
- Set the figure size and adjust the padding between and around the subplots.
- Make a data frame, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
- Add a subplot to the current figure.
- Make a bar plot with the dataframe, df.
- Add a subplot to the current figure.
- Make a df_sorted by a column marks.
- Make a bar plot with df_sorted.
- To display the figure, use show() method.
Example
import pandas as pd from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame( dict( names=['John', 'James', 'David', 'Gary', 'Watson'], marks=[23, 34, 30, 19, 20] ) ) plt.subplot(121) plt.bar('names', 'marks', data=df, color='red') plt.subplot(122) df_sorted = df.sort_values('marks') plt.bar('names', 'marks', data=df_sorted, color='orange') plt.show()
Output
It will produce the following output
Notice the bar chart on the right. The bars are sorted in the increasing order of their values.
Advertisements