Python bar plot color

Control the color of barplots built with matplotlib

This post aims to describe how to use colors on matplotlib barplots.

Uniform color using RGB

You can change the color of bars in a barplot using color argument.
RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.

# libraries import numpy as np import matplotlib.pyplot as plt # create a dataset height = [3, 12, 5, 18, 45] bars = ('A', 'B', 'C', 'D', 'E') x_pos = np.arange(len(bars)) # Create bars plt.bar(x_pos, height, color=(0.2, 0.4, 0.6, 0.6)) # Create names on the x-axis plt.xticks(x_pos, bars) # Show graph plt.show()

Different color for each bar

If you want to give different colors to each bar, just provide a list of color names to the color argument:

# libraries import numpy as np import matplotlib.pyplot as plt # create a dataset height = [3, 12, 5, 18, 45] bars = ('A', 'B', 'C', 'D', 'E') x_pos = np.arange(len(bars)) # Create bars with different colors plt.bar(x_pos, height, color=['black', 'red', 'green', 'blue', 'cyan']) # Create names on the x-axis plt.xticks(x_pos, bars) # Show graph plt.show()

Control color of border

The edgecolor argument allows you to color the borders of barplots.

# libraries import numpy as np import matplotlib.pyplot as plt # create a dataset height = [3, 12, 5, 18, 45] bars = ('A', 'B', 'C', 'D', 'E') x_pos = np.arange(len(bars)) # Create bars with blue edge color plt.bar(x_pos, height, color=(0.1, 0.1, 0.1, 0.1), edgecolor='blue') # Create names on the x-axis plt.xticks(x_pos, bars) # Show graph plt.show()

Источник

Setting Different Bar color in matplotlib Python [duplicate]

BarPlot

Supposely, I have the bar chart as below: Any ideas on how to set different colors for each carrier? As for example, AK would be Red, GA would be Green, etc? I am using Pandas and matplotlib in Python

>>> f=plt.figure() >>> ax=f.add_subplot(1,1,1) >>> ax.bar([1,2,3,4], [1,2,3,4]) >>> ax.get_children() [, , , , , , , , , , , ] >>> ax.get_children()[2].set_color('r') #You can also try to locate the first patches.Rectangle object instead of direct calling the index. 

For the suggestions above, how do exactly we could enumerate ax.get_children() and check if the object type is rectangle? So if the object is rectangle, we would assign different random color?

my_colors = [‘brown’,’pink’, ‘red’, ‘green’, ‘blue’, ‘cyan’,’orange’,’purple’] plt.bar(yourX,yourY ,color=my_colors)

3 Answers 3

Simple, just use .set_color

>>> barlist=plt.bar([1,2,3,4], [1,2,3,4]) >>> barlist[0].set_color('r') >>> plt.show() 

enter image description here

For your new question, not much harder either, just need to find the bar from your axis, an example:

>>> f=plt.figure() >>> ax=f.add_subplot(1,1,1) >>> ax.bar([1,2,3,4], [1,2,3,4]) >>> ax.get_children() [, , , , , , , , , , , ] >>> ax.get_children()[2].set_color('r') #You can also try to locate the first patches.Rectangle object #instead of direct calling the index. 

If you have a complex plot and want to identify the bars first, add those:

>>> import matplotlib >>> childrenLS=ax.get_children() >>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS) [, , , , ] 

Thanks for your reply. However, I get the barplot from: dfPlotSum.plot(kind=»bar», title=titleStr, legend=False) This function would return ax object. Any idea on how to set the color on this way? Thanks!

Читайте также:  Css class after classes

See edit, this is a simple plot so I know the first bar has the index of 2. If you are dealing with a complex plot, you have to locate the bar you want to change first. Can’t be more specific as I don’t have your dfPlotSum.plot() , but the idea is the same.

Notice that this removes the black border (edge) of the bar. It can be brought back by using: barlist[0].set_edgecolor(«black») . A better way might be to use barlist[0].set_facecolor(‘r’) which does not change the edge of the bar.

@SantiagoMunez just put the plot in a variable and call .get_children() function, like this: ax = dfPlotSum.plot(kind=»bar», title=titleStr, legend=False) and then ax.get_children()[3].set_color(‘r’)

I tried to plot bar with barlist=plt.bar([‘a’,’b’,’c’,’d’], [1,2,3,4]) but failed with barlist[‘a’].set_color(‘r’) .

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

there is no color parameter listed where you might be able to set the colors for your bar graph.

However, the Series.plot() docs state the following at the end of the parameter list:

kwds : keywords Options to pass to matplotlib plotting method 

What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

If you examine the docs for the matplotlib.pyplot.bar() method here:

..it also accepts keyword arguments at the end of it’s parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

import pandas as pd import matplotlib.pyplot as plt s = pd.Series( [5, 4, 4, 1, 12], index = ["AK", "AX", "GA", "SQ", "WN"] ) #Set descriptions: plt.title("Total Delay Incident Caused by Carrier") plt.ylabel('Delay Incident') plt.xlabel('Carrier') #Set tick colors: ax = plt.gca() ax.tick_params(axis='x', colors='blue') ax.tick_params(axis='y', colors='red') #Plot the data: my_colors = 'rgbkymc' #red, green, blue, black, etc. pd.Series.plot( s, kind='bar', color=my_colors, ) plt.show() 

enter image description here

Note that if there are more bars than colors in your sequence, the colors will repeat.

Источник

Читайте также:  METANIT.COM

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.

Читайте также:  Prompt user for name javascript

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:

Источник

Оцените статью