- How to set Bar Color(s) for Bar Chart in Matplotlib?
- Examples
- Single Color for All Bars
- HEX Color
- Different Colors for Bars
- Summary
- matplotlib.pyplot.bar#
- Matplotlib Bar Plot — Tutorial and Examples
- Plot a Bar Plot in Matplotlib
- Plot a Horizontal Bar Plot in Matplotlib
- Change Bar Plot Color in Matplotlib
- Bar Plot with Error Bars in Matplotlib
- Free eBook: Git Essentials
- Plot Stacked Bar Plot in Matplotlib
- Conclusion
How to set Bar Color(s) for Bar Chart in Matplotlib?
To set color for bars in Bar chart in Matplotlib, set color parameter with required color value when calling bar() function.
We can provide a single color value, or a list of colors to the color parameter. We shall look into these scenarios in detail with examples.
We can provide inbuilt color values like ‘red’, ‘green’, ‘yellow’, etc., or a HEX value like ‘#FA08A5’, ‘#140895’, etc.
ax.bar(x, height, color='green') ax.bar(x, height, color='#FA08A5') ax.bar(x, height, color=['green', 'red']) ax.bar(x, height, color=['green', '#256A96'])
Examples
Single Color for All Bars
In the following example, we draw a bar plot with the color of all bars set to ‘green’.
Python Program
import matplotlib.pyplot as plt x = [2011, 2012, 2013, 2014, 2015, 2016] height = [5.6, 7, 2.5, 4, 3.8, 6.1] fig, ax = plt.subplots() ax.bar(x, height, color='green') ax.set_xlabel('Time') ax.set_ylabel('Price') ax.set_title('XY Stock') plt.show()
HEX Color
In the following example, we draw a bar plot with the color of all bars set to the HEX value ‘green’.
Python Program
import matplotlib.pyplot as plt x = [2011, 2012, 2013, 2014, 2015, 2016] height = [5.6, 7, 2.5, 4, 3.8, 6.1] fig, ax = plt.subplots() ax.bar(x, height, color='#4958B5') ax.set_xlabel('Time') ax.set_ylabel('Price') ax.set_title('XY Stock') plt.show()
Different Colors for Bars
In the following example, we draw a bar plot with different colors for bars. The color parameter takes the color values as a list.
If the number of colors in the list is less than the number of bars, the colors from the beginning of the list are used in a cyclic manner.
Python Program
import matplotlib.pyplot as plt x = [2011, 2012, 2013, 2014, 2015, 2016] height = [5.6, 7, 2.5, 4, 3.8, 6.1] fig, ax = plt.subplots() ax.bar(x, height, color=['#C94845', '#4958B5', '#49D845', '#777777']) ax.set_xlabel('Time') ax.set_ylabel('Price') ax.set_title('XY Stock') plt.show()
Summary
In this tutorial of Python Examples, we learned how to set color of bars in Bar Chart in Matplotlib.
matplotlib.pyplot.bar#
The bars are positioned at x with the given alignment. Their dimensions are given by height and width. The vertical baseline is bottom (default 0).
Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar.
Parameters : x float or array-like
The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.
height float or array-like
width float or array-like, default: 0.8
bottom float or array-like, default: 0
The y coordinate(s) of the bottom side(s) of the bars.
align , default: ‘center’
Alignment of the bars to the x coordinates:
- ‘center’: Center the base on the x positions.
- ‘edge’: Align the left edges of the bars with the x positions.
To align the bars on the right edge pass a negative width and align=’edge’ .
Container with all the bars and optionally errorbars.
Other Parameters : color color or list of color, optional
The colors of the bar faces.
edgecolor color or list of color, optional
The colors of the bar edges.
linewidth float or array-like, optional
Width of the bar edge(s). If 0, don’t draw edges.
tick_label str or list of str, optional
The tick labels of the bars. Default: None (Use default numeric labels.)
label str or list of str, optional
A single label is attached to the resulting BarContainer as a label for the whole dataset. If a list is provided, it must be the same length as x and labels the individual bars. Repeated labels are not de-duplicated and will cause repeated label entries, so this is best used when bars also differ in style (e.g., by passing a list to color.)
xerr, yerr float or array-like of shape(N,) or shape(2, N), optional
If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:
- scalar: symmetric +/- values for all bars
- shape(N,): symmetric +/- values for each bar
- shape(2, N): Separate — and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
- None: No errorbar. (Default)
See Different ways of specifying error bars for an example on the usage of xerr and yerr.
ecolor color or list of color, default: ‘black’
The line color of the errorbars.
capsize float, default: rcParams[«errorbar.capsize»] (default: 0.0 )
The length of the error bar caps in points.
error_kw dict, optional
Dictionary of keyword arguments to be passed to the errorbar method. Values of ecolor or capsize defined here take precedence over the independent keyword arguments.
log bool, default: False
If True, set the y-axis to be log scale.
data indexable object, optional
If given, all parameters also accept a string s , which is interpreted as data[s] (unless this raises an exception).
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
Matplotlib Bar Plot — Tutorial and Examples
Matplotlib is one of the most widely used data visualization libraries in Python. From simple to complex visualizations, it’s the go-to library for most.
In this tutorial, we’ll take a look at how to plot a bar plot in Matplotlib.
Bar graphs display numerical quantities on one axis and categorical variables on the other, letting you see how many occurrences there are for the different categories.
Bar charts can be used for visualizing a time series, as well as just categorical data.
Plot a Bar Plot in Matplotlib
Plotting a Bar Plot in Matplotlib is as easy as calling the bar() function on the PyPlot instance, and passing in the categorical and numerical variables that we’d like to visualize.
import matplotlib.pyplot as plt x = ['A', 'B', 'C'] y = [1, 5, 3] plt.bar(x, y) plt.show()
Here, we’ve got a few categorical variables in a list — A , B and C . We’ve also got a couple of continuous variables in another list — 1 , 5 and 3 . The relationship between these two is then visualized in a Bar Plot by passing these two lists to plt.bar() .
This results in a clean and simple bar graph:
Plot a Horizontal Bar Plot in Matplotlib
Oftentimes, we might want to plot a Bar Plot horizontally, instead of vertically. This is easily achievable by switching the plt.bar() call with the plt.barh() call:
import matplotlib.pyplot as plt x = ['A', 'B', 'C'] y = [1, 5, 3] plt.barh(x, y) plt.show()
This results in a horizontally-oriented Bar Plot:
Change Bar Plot Color in Matplotlib
Changing the color of the bars themselves is as easy as setting the color argument with a list of colors. If you have more bars than colors in the list, they’ll start being applied from the first color again:
import matplotlib.pyplot as plt x = ['A', 'B', 'C'] y = [1, 5, 3] plt.bar(x, y, color=['red', 'blue', 'green']) plt.show()
Now, we’ve got a nicely colored Bar Plot:
Of course, you can also use the shorthand versions or even HTML codes:
plt.bar(x, y, color=['red', 'blue', 'green']) plt.bar(x, y, color=['r', 'b', 'g']) plt.bar(x, y, color=['#ff0000', '#00ff00', '#0000ff']) plt.show()
Or you can even put a single scalar value, to apply it to all bars:
Bar Plot with Error Bars in Matplotlib
When you’re plotting mean values of lists, which is a common application for Bar Plots, you’ll have some error space. It’s very useful to plot error bars to let other observers, and yourself, know how truthful these means are and which deviation is expected.
For this, let’s make a dataset with some values, calculate their means and standard deviations with NumPy and plot them with error bars:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
import matplotlib.pyplot as plt import numpy as np x = np.array([4, 5, 6, 3, 6, 5, 7, 3, 4, 5]) y = np.array([3, 4, 1, 3, 2, 3, 3, 1, 2, 3]) z = np.array([6, 9, 8, 7, 9, 8, 9, 6, 8, 7]) x_mean = np.mean(x) y_mean = np.mean(y) z_mean = np.mean(z) x_deviation = np.std(x) y_deviation = np.std(y) z_deviation = np.std(z) bars = [x_mean, y_mean, z_mean] bar_categories = ['X', 'Y', 'Z'] error_bars = [x_deviation, y_deviation, z_deviation] plt.bar(bar_categories, bars, yerr=error_bars) plt.show()
Here, we’ve created three fake datasets with several values each. We’ll visualize the mean values of each of these lists. However, since means, as well as averages can give the false sense of accuracy, we’ll also calculate the standard deviation of these datasets so that we can add those as error bars.
Using NumPy’s mean() and std() functions, this is a breeze. Then, we’ve packed the bar values into a bars list, the bar names for a nice user experience into bar_categories and finally — the standard deviation values into an error_bars list.
To visualize this, we call the regular bar() function, passing in the bar_categories (categorical values) and bars (continuous values), alongside the yerr argument.
Since we’re plotting vertically, we’re using the yerr argument. If we were plotting horizontally, we’d use the xerr argument. Here, we’ve provided the information about the error bars.
This ultimately results in:
Plot Stacked Bar Plot in Matplotlib
Finally, let’s plot a Stacked Bar Plot. Stacked Bar Plots are really useful if you have groups of variables, but instead of plotting them one next to the other, you’d like to plot them one on top of the other.
For this, we’ll again have groups of data. Then, we’ll calculate their standard deviation for error bars.
Finally, we’ll need an index range to plot these variables on top of each other, while maintaining their relative order. This index will essentially be a range of numbers the length of all the groups we’ve got.
To stack a bar on another one, you use the bottom argument. You specify what’s on the bottom of that bar. To plot x beneath y , you’d set x as the bottom of y .
For more than one group, you’ll want to add the values together before plotting, otherwise, the Bar Plot won’t add up. We’ll use NumPy’s np.add().tolist() to add the elements of two lists and produce a list back:
import matplotlib.pyplot as plt import numpy as np # Groups of data, first values are plotted on top of each other # Second values are plotted on top of each other, etc x = [1, 3, 2] y = [2, 3, 3] z = [7, 6, 8] # Standard deviation rates for error bars x_deviation = np.std(x) y_deviation = np.std(y) z_deviation = np.std(z) bars = [x, y, z] ind = np.arange(len(bars)) bar_categories = ['X', 'Y', 'Z']; bar_width = 0.5 bar_padding = np.add(x, y).tolist() plt.bar(ind, x, yerr=x_deviation, width=bar_width) plt.bar(ind, y, yerr=y_deviation, bottom=x, width=bar_width) plt.bar(ind, z, yerr=z_deviation, bottom=bar_padding, width=bar_width) plt.xticks(ind, bar_categories) plt.xlabel("Stacked Bar Plot") plt.show()
Running this code results in:
Conclusion
In this tutorial, we’ve gone over several ways to plot a bar plot using Matplotlib and Python. We’ve also covered how to calculate and add error bars, as well as stack bars on top of each other.
If you’re interested in Data Visualization and don’t know where to start, make sure to check out our bundle of books on Data Visualization in Python: