Python horizontal bar chart

Matplotlib Bar chart

Matplotlib may be used to create bar charts. You might like the Matplotlib gallery.

Matplotlib is a python library for visualizing data. You can use it to create bar charts in python. Installation of matplot is on pypi, so just use pip: pip install matplotlib

The course below is all about data visualization:

Bar chart code

A bar chart shows values as vertical bars, where the position of each bar indicates the value it represents. matplot aims to make it as easy as possible to turn data into Bar Charts.

A bar chart in matplotlib made from python code. The code below creates a bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = (‘Python’, ‘C++’, ‘Java’, ‘Perl’, ‘Scala’, ‘Lisp’)
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.bar(y_pos, performance, align=‘center’, alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel(‘Usage’)
plt.title(‘Programming language usage’)

plt.show()

figure_barchart

Matplotlib charts can be horizontal, to create a horizontal bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = (‘Python’, ‘C++’, ‘Java’, ‘Perl’, ‘Scala’, ‘Lisp’)
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.barh(y_pos, performance, align=‘center’, alpha=0.5)
plt.yticks(y_pos, objects)
plt.xlabel(‘Usage’)
plt.title(‘Programming language usage’)

plt.show()

Bar chart horizontal

Bar chart comparison

You can compare two data series using this Matplotlib code:

import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 4
means_frank = (90, 55, 40, 65)
means_guido = (85, 62, 54, 20)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color=‘b’,
label=‘Frank’)

rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color=‘g’,
label=‘Guido’)

plt.xlabel(‘Person’)
plt.ylabel(‘Scores’)
plt.title(‘Scores by person’)
plt.xticks(index + bar_width, (‘A’, ‘B’, ‘C’, ‘D’))
plt.legend()

plt.tight_layout()
plt.show()

barchart_python

Python Bar Chart comparison

Stacked bar chart

The example below creates a stacked bar chart with Matplotlib. Stacked bar plots show diffrent groups together.

# load matplotlib
import matplotlib.pyplot as plt

# data set
x = [‘A’, ‘B’, ‘C’, ‘D’]
y1 = [100, 120, 110, 130]
y2 = [120, 125, 115, 125]

# plot stacked bar chart
plt.bar(x, y1, color=‘g’)
plt.bar(x, y2, bottom=y1, color=‘y’)
plt.show()

Источник

Horizontal bar chart#

This example showcases a simple horizontal bar chart.

How fast do you want to go today?

import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) ax.barh(y_pos, performance, xerr=error, align='center') ax.set_yticks(y_pos, labels=people) ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Performance') ax.set_title('How fast do you want to go today?') plt.show() 

Источник

How to Create a Horizontal Bar Chart using Matplotlib

Data to Fish

Here is a simple template that you can use to create a horizontal bar chart using Matplotlib:

import matplotlib.pyplot as plt y_axis = ['value_1', 'value_2', 'value_3', . ] x_axis = ['value_1', 'value_2', 'value_3', . ] plt.barh(y_axis, x_axis) plt.title('title name') plt.ylabel('y axis name') plt.xlabel('x axis name') plt.show()

Later, you’ll also see how to plot a horizontal bar chart with the help of the Pandas library.

Steps to Create a Horizontal Bar Chart using Matplotlib

Step 1: Gather the data for the chart

For example, let’s use the data below to plot the chart:

product quantity
computer 320
monitor 450
laptop 300
printer 120
tablet 280

The above data can be captured in Python using lists:

product = ['computer', 'monitor', 'laptop', 'printer', 'tablet'] quantity = [320, 450, 300, 120, 280] print(product) print(quantity)

If you run the code in Python, you’ll get the following lists:

['computer', 'monitor', 'laptop', 'printer', 'tablet'] [320, 450, 300, 120, 280] 

Step 2: Plot the horizontal bar chart using Matplotlib

You can then plot the chart using this syntax:

import matplotlib.pyplot as plt product = ['computer', 'monitor', 'laptop', 'printer', 'tablet'] quantity = [320, 450, 300, 120, 280] plt.barh(product, quantity) plt.title('store inventory') plt.ylabel('product') plt.xlabel('quantity') plt.show()

Run the code in Python, and you’ll see the ‘product‘ on the y_axis, and the ‘quantity‘ on the x_axis.

Step 3 (optional): Style the chart

You can further style the chart by including the following syntax:

So the complete code would look as follows:

import matplotlib.pyplot as plt product = ['computer', 'monitor', 'laptop', 'printer', 'tablet'] quantity = [320, 450, 300, 120, 280] plt.style.use('ggplot') plt.barh(product, quantity) plt.title('store inventory') plt.ylabel('product') plt.xlabel('quantity') plt.show()

Plot the Horizontal Bar Chart with the Help of Pandas

You can plot the same bar chart with the help of the Pandas library:

import matplotlib.pyplot as plt import pandas as pd data = df = pd.DataFrame(data, index=['computer', 'monitor', 'laptop', 'printer', 'tablet']) df.plot.barh() plt.title('store inventory') plt.ylabel('product') plt.xlabel('quantity') plt.show()

Once you run the code, you’ll get the same bar chart.

Let’s say that you also want to capture the ‘price‘ (in addition to the ‘quantity’) associated with the product.

In that case, you can use the code below in order to create the horizontal bar chart with both the price and the quantity:

import matplotlib.pyplot as plt import pandas as pd data = df = pd.DataFrame(data, index=['computer', 'monitor', 'laptop', 'printer', 'tablet']) df.plot.barh() plt.title('store inventory') plt.ylabel('product') plt.xlabel('quantity') plt.show()

You can further style the chart using:

import matplotlib.pyplot as plt import pandas as pd data = df = pd.DataFrame(data, index=['computer', 'monitor', 'laptop', 'printer', 'tablet']) plt.style.use('ggplot') df.plot.barh() plt.title('store inventory') plt.ylabel('product') plt.xlabel('quantity') plt.show()

You can learn more about plotting charts by visiting the Matplotlib Documentation.

Источник

Читайте также:  Each php чем заменить
Оцените статью