Error bars in charts you create can help you see margins of error and standard deviations at a glance. They can be shown on all data points or data markers in a data series as a standard error amount, a percentage, or a standard deviation. You can set your own values to display the exact error amounts you want. For example, you can show a 10 percent positive and negative error amount in the results of a scientific experiment like this:
You can use error bars in 2-D area, bar, column, line, xy (scatter), and bubble charts. In scatter and bubble charts, you can show error bars for x and y values.
Note: The following procedures apply to Office 2013 and newer versions. Looking for Office 2010 steps?
Add or remove error bars
-
Click anywhere in the chart.
-
Click the Chart Elements button next to the chart, and then check the Error Bars box. (Clear the box to remove error bars.)
-
To change the error amount shown, click the arrow next to Error Bars, and then pick an option.
-
Pick a predefined error bar option like Standard Error, Percentage or Standard Deviation.
-
Pick More Options to set your own error bar amounts, and then under Vertical Error Bar or Horizontal Error Bar, choose the options you want. This is also where you can change the direction, end style of the error bars, or create custom error bars.
-
Note: The direction of the error bars depends on the type of chart you’re using. Scatter charts can show both horizontal and vertical error bars. You can remove either of these error bars by selecting them, and then pressing Delete.
Review equations for calculating error amounts
People often ask how Excel calculates error amounts. Excel uses the following equations to calculate the Standard Error and Standard Deviation amounts that are shown on the chart.
This option |
Uses this equation |
---|---|
Standard Error |
Where: s = series number i = point number in series s m = number of series for point y in chart n = number of points in each series yis = data value of series s and the ith point ny = total number of data values in all series |
Standard Deviation |
Where: s = series number i = point number in series s m = number of series for point y in chart n = number of points in each series yis = data value of series s and the ith point ny = total number of data values in all series M = arithmetic mean |
Add, change, or remove errors bars in a chart in Office 2010
In Excel, you can display error bars that use a standard error amount, a percentage of the value (5%), or a standard deviation.
Standard Error and Standard Deviation use the following equations to calculate the error amounts that are shown on the chart.
This option |
Uses this equation |
Where |
---|---|---|
Standard Error |
|
s = series number i = point number in series s m = number of series for point y in chart n = number of points in each series yis = data value of series s and the ith point ny = total number of data values in all series |
Standard Deviation |
|
s = series number i = point number in series s m = number of series for point y in chart n = number of points in each series yis = data value of series s and the ith point ny = total number of data values in all series M = arithmetic mean |
-
On 2-D area, bar, column, line, xy (scatter), or bubble chart, do one of the following:
-
To add error bars to all data series in the chart, click the chart area.
-
To add error bars to a selected data point or data series, click the data point or data series that you want, or do the following to select it from a list of chart elements:
-
Click anywhere in the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
-
On the Format tab, in the Current Selection group, click the arrow next to the Chart Elements box, and then click the chart element that you want.
-
-
-
On the Layout tab, in the Analysis group, click Error Bars.
-
Do one of the following:
-
Click a predefined error bar option, such as Error Bars with Standard Error, Error Bars with Percentage, or Error Bars with Standard Deviation.
-
Click More Error Bar Options, and then under Vertical Error Bars or Horizontal Error Bars, click the display and error amount options that you want to use.
Note: The direction of the error bars depends on the chart type of your chart. For scatter charts, both horizontal and vertical error bars are displayed by default. You can remove either of these error bars by selecting them, and then pressing DELETE.
-
-
On a 2-D area, bar, column, line, xy (scatter), or bubble chart, click the error bars, the data point, or the data series that has the error bars that you want to change, or do the following to select them from a list of chart elements:
-
Click anywhere in the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
-
On the Format tab, in the Current Selection group, click the arrow next to the Chart Elements box, and then click the chart element that you want.
-
-
On the Layout tab, in the Analysis group, click Error Bars, and then click More Error Bar Options.
-
Under Display, click the error bar direction and end style that you want to use.
-
On a 2-D area, bar, column, line, xy (scatter), or bubble chart, click the error bars, the data point, or the data series that has the error bars that you want to change, or do the following to select them from a list of chart elements:
-
Click anywhere in the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
-
On the Format tab, in the Current Selection group, click the arrow next to the Chart Elements box, and then click the chart element that you want.
-
-
On the Layout tab, in the Analysis group, click Error Bars, and then click More Error Bar Options.
-
Under Error Amount, do one or more of the following:
-
To use a different method to determine the error amount, click the method that you want to use, and then specify the error amount.
-
To use custom values to determine the error amount, click Custom, and then do the following:
-
Click Specify Value.
-
In the Positive Error Value and Negative Error Value boxes, specify the worksheet range that you want to use as error amount values, or type the values that you want to use, separated by commas. For example, type 0.4, 0.3, 0.8.
Tip: To specify the worksheet range, you can click the Collapse Dialog button , and then select the data that you want to use in the worksheet. Click the Collapse Dialog button again to return to the dialog box.
Note: In Microsoft Office Word 2007 or Microsoft Office PowerPoint 2007, the Custom Error Bars dialog box may not show the Collapse Dialog button, and you can only type the error amount values that you want to use.
-
-
-
On a 2-D area, bar, column, line, xy (scatter), or bubble chart, click the error bars, the data point, or the data series that has the error bars that you want to remove, or do the following to select them from a list of chart elements:
-
Click anywhere in the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
-
On the Format tab, in the Current Selection group, click the arrow next to the Chart Elements box, and then click the chart element that you want.
-
-
Do one of the following:
-
On the Layout tab, in the Analysis group, click Error Bars, and then click None.
-
Press DELETE.
-
Tip: You can remove error bars immediately after you add them to the chart by clicking Undo on the Quick Access Toolbar or by pressing CTRL+Z.
Do any of the following:
Express errors as a percentage, standard deviation, or standard error
-
In the chart, select the data series that you want to add error bars to.
For example, in a line chart, click one of the lines in the chart, and all the data marker of that data series become selected.
-
On the Chart Design tab, click Add Chart Element.
-
Point to Error Bars, and then do one of the following:
Click |
To |
---|---|
Standard Error |
Apply the standard error, using the following formula:
s = series number |
Percentage |
Apply a percentage of the value for each data point in the data series |
Standard Deviation |
Apply a multiple of the standard deviation, using the following formula:
s = series number |
Express errors as custom values
-
In the chart, select the data series that you want to add error bars to.
-
On the Chart Design tab, click Add Chart Element, and then click More Error Bars Options.
-
In the Format Error Bars pane, on the Error Bar Options tab, under Error Amount, click Custom, and then click Specify Value.
-
Under Error amount, click Custom, and then click Specify Value.
-
In the Positive Error Value and Negative Error Value boxes, type the values that you want for each data point, separated by commas (for example, 0.4, 0.3, 0.8), and then click OK.
Note: You can also define error values as a range of cells from the same Excel workbook. To select the range of cells, in the Custom Error Bars dialog box, clear the contents of the Positive Error Value or Negative Error Value box, and then select the range of cells that you want to use.
Add up/down bars
-
In the chart, select the data series that you want to add up/down bars to.
-
On the Chart Design tab, click Add Chart Element, point to Up/Down Bars, and then click Up/down Bars.
Depending on the chart type, some options may not be available.
See Also
Create a chart
Change the chart type of an existing chart
When you represent data in a chart, there can be cases when there is a level of variability with a data point.
For example, you can not (with 100% certainty) predict the temperature of the next 10 days or the stock price of a company in the coming week.
There will always be a level of variability in the data. The final value could be a little higher or lower.
If you have to represent this kind of data, you can use Error Bars in the Charts in Excel.
What are Error Bars?
Error bars are the bars in an Excel chart that would represent the variability of a data point.
This will give you an idea of how accurate is the data point (measurement). It tells you how far the actual can go from the reported value (higher or lower).
For example, in the below chart, I have the sales estimates for the four quarters, and there is an error bar for each of the quarter bar. Each error bar indicates how much less or more the sales can be for each quarter.
The more the variability, the less accurate is the data point in the chart.
I hope this gives you an overview of what is an error bar and how to use an error bar in Excel charts. Now let me show you how to add these error bars in Excel charts.
How to Add Error Bars in Excel Charts
In Excel, you can add error bars in a 2-D line, bar, column or area chart. You can also add it to the XY scatter chart or a bubble chart.
Suppose you have a dataset and the chart (created using this dataset) as shown below and you want to add error bars to this dataset:
Below are the steps to add data bars in Excel (2019/2016/2013):
- Click anywhere in your chart. It will make available the three icons as shown below.
- Click on the plus icon (the Chart Element icon)
- Click on the black triangle icon at the right of ‘Error bars’ option (it appears when you hover the cursor on the ‘Error Bars’ option)
- Choose from the three options (Standard Error, Percentage, or Standard Deviation), or click on ‘More Options’ to get even more options. In this example, I am clicking on Percentage option
The above steps would add the Percentage error bar to all the four columns in the chart.
By default, the value of the percentage error bar is 5%. This means that it will create an error bar that goes a maximum of 5% above and below the current value.
Types of Error Bars in Excel Charts
As you saw in the steps above that there are different types of error bars in Excel.
So let’s go through these one-by-one (and more on these later as well).
‘Standard Error’ Error Bar
This shows the ‘standard error of the mean’ for all values. This error bar tells us how far the mean of the data is likely to be from the true population mean.
This is something you may need if you work with statistical data.
‘Percentage’ Error Bar
This one is simple. It will show the specified percentage variation in each data point.
For example, in our chart above, we added the percentage error bars where the percentage value was 5%. This would mean that if your data point value is 100, the error bar will be from 95 to 105.
‘Standard Deviation’ Error Bar
This shows how close the bar is to the mean of the dataset.
The error bars, in this case, are all in the same position (as shown below). And for each column, you can see how much is the variation from the overall mean of the dataset.
By default, Excel plots these error bars with a value of standard deviation as 1, but you can change this if you want (by going to the More Options and then changing the value in the pane that opens).
‘Fixed Value’ Error Bar
This, as the name suggests, shows the error bars where the error margin is fixed.
For example, in the quarterly sales example, you can specify the error bars to be 100 units. It will then create an error bar where the value can deviate from -100 to +100 units (as shown below).
‘Custom’ Error Bar
In case you want to create your own custom error bars, where you specify the upper and lower limit for each data point, you can do that using the custom error bars option.
You can choose to keep the range the same for all error bars, or can also make individual custom error bars for each data point (example covered later in this tutorial).
This could be useful when you have a different level of variability of each data point. For example, I may be quite confident about sales numbers in Q1 (i.e, low variability) and less confident about sales numbers in Q3 and Q4 (i.e., high variability). In such cases, I can use custom error bars to show the custom variability in each data point.
Now, let’s dive into more into how to add custom error bars in Excel charts.
Adding Custom Error Bars in Excel Charts
Error bars other than the custom error bars (i.e., fixed, percentage, standard deviation, and standard error) are all quite straightforward to apply. You need to just select the option and specify a value (if needed).
Custom error bars need a little more work.
With custom error bars, there could be two scenarios:
- All data point have the same variability
- Every data point has its own variability
Let’s see how to do each of these in Excel
Custom Error Bars – Same Variability for all Data Points
Suppose you have the data set as shown below and a chart associated with this data.
Below are the steps to create custom error bars (where the error value is the same for all data points):
- Click anywhere in your chart. It will make available the three chart option icons.
- Click on the plus icon (the Chart Element icon)
- Click on the black triangle icon at the right of ‘Error bars’ option
- Choose on ‘More Options’
- In the ‘Format Error Bars’ pane, check the Custom option
- Click on the ‘Specify Value’ button.
- In the Custom Error dialog box that opens, enter the positive and negative error value. You can delete the existing value in the field and enter the value manually (without any equal to sign or brackets). In this example, I am using 50 as the error bar value.
- Click OK
This would apply the same custom error bars for each column in the column chart.
Custom Error Bars – Different Variability for all Data Points
In case you want to have different error values for each data point, you need to have these values in a range in Excel and then you can refer to that range.
For example, suppose I have manually calculated the positive and negative error values for each data point (as shown below) and I want these to be the plotted as error bars.
Below are the steps to do this:
- Create a column chart using the sales data
- Click anywhere in your chart. It will make available the three icons as shown below.
- Click on the plus icon (the Chart Element icon)
- Click on the black triangle icon at the right of ‘Error bars’ option
- Choose on ‘More Options’
- In the ‘Format Error Bars’ pane, check the Custom option
- Click on the ‘Specify Value’ button.
- In the Custom Error dialog box that opens, click on the range selector icon for the Positive Error Value and then select the range that has these values (C2:C5 in this example)
- Now, click on the range selector icon for the Negative Error Value and then select the range that has these values (D2:D5 in this example)
- Click OK
The above steps would give you custom error bars for each data point based on the selected values.
Note that each column in the above chart has a different size error bar as these have been specified using the values in the ‘Positive EB’ and ‘Negative EB’ columns in the dataset.
In case you change any of the values later, the chart would automatically update.
Formatting the Error Bars
There are a few things you can do to format and modify the error bars. These include the color, thickness of the bar, and the shape of it.
To format an error bar, right-click on any of the bars and then click on ‘Format Error bars’. This will open the ‘Format Error Bars’ pane on the right.
Below are the things you can format/modify in an error bar:
Color/width of the Error bar
This can be done by selecting the ‘Fill and Line’ option in then changing the color and/or width.
You can also change the dash type in case you want to make your error bar look different than a solid line.
One example where this could be useful is when you want to highlight the error bars and not the data points. In that case, you can make everything else light in color to make the error bars pop-out
Direction/Style of the Error bar
You can choose to show error bars that go both sides of the data point (positive and negative), you can choose to only show the plus or minus error bars.
These options can be changed from the Direction option in the ‘Format Error Bars’ pane.
Another thing you can change is whether you want the end of the bar to have a cap or not. Below is an example where the chart on the left has the cap and one on the right doesn’t
Adding Horizontal Error Bars in Excel Charts
So far, we have seen the vertical error bars. which are the most common in Excel charting (and can be used with column charts, line charts, area charts, scatter charts)
But you can also add and use horizontal error bars. These can be used with bar charts as well as the scatter charts.
Below is an example, where I have plotted the quarterly data into a bar chart.
The method of adding the horizontal error bars is the same as that of vertical error bars that we saw in the sections above.
You can also add horizontal (as well as vertical error bars) to scatter charts or bubble charts. Below is an example where I have plotted the sales and profit values in a scatter chart and have added both vertical and horizontal error bars.
You can also format these error bars (horizontal or vertical) separately. For example, you may want to show a percentage error bar for horizontal error bars and custom error bars for vertical ones.
Adding Error Bars to a Series in a Combo Chart
If you work with combo charts, you can add error bars to any one of the series.
For example, below is an example of a combo chart where I have plotted the sales values as columns and profit as a line chart. And an error bar has only been added to the line chart.
Below are the steps to add error bars to a specific series only:
- Select the series for which you want to add the error bars
- Click on the plus icon (the Chart Element icon)
- Click on the black triangle icon at the right of ‘Error bars’ option
- Choose the error bar that you want to add.
If you want, you can also add error bars to all the series in the chart. Again, follow the same steps where you need to select the series for which you want to add the error bar in the first step.
Note: There is no way to add an error bar only to one specific data point. When you add it to a series, it’s added to all the data points in the chart for that series.
Deleting the Error bars
Deleting the error bars is quite straightforward.
Just select the error bar that you want to delete, and hit the delete key.
When you do this, it will delete all the error bars for that series.
If you have both horizontal and vertical error bars, you can choose to delete only one of these (again by simply selecting and hitting the Delete key).
So this is all that you need to know about adding error bars in Excel.
Hope you found this tutorial useful!
You may also like the following Excel tutorials:
- How to Create a Timeline / Milestone Chart in Excel
- How to Create a Dynamic Chart Range in Excel
- Creating a Pareto Chart in Excel
- Creating an Actual vs Target Chart in Excel
- How to Make a Histogram in Excel
- How to Find Slope in Excel?
Monday, August 30, 2010
Peltier Technical Services, Inc., Copyright © 2023, All rights reserved.
I’ve written about Excel chart error bars in Error Bars in Excel Charts for Classic Excel and in Error Bars in Excel 2007 Charts for New Excel. Both articles contained instructions for adding custom error bar values for individual points, but judging from the emails I receive, a separate article on custom error bars is needed. You cannot add custom error bar values to a single point in a chart. However, you can individual custom error bar values to all points in a plotted series. You need to put all of the individual error bar values into a range of the worksheet. I usually put these values in the same table as the actual X and Y values
Manually Defining Custom Error Bars
Sample Data and Charts
Suppose we have the following data: X and Y values, plus extra columns with positive and negative error bar values for both X and Y directions. The data is set up so that, for example, cells C2 and D2 have the values for the positive and negative horizontal (X) error bars for the point defined by X and Y values in A2 and B2. Cells E2 and F2 have the values for the positive and negative vertical (Y) error bars for this point. The series is plotted using all the data at once, with X in A2:A6 and Y in B2:6. The error bars are also drawn using all the error bar data at once: C2:C6 and D2:D6 for horizontal and E2:E6 and F2:F6 for vertical.
The chart itself is easy: create an XY chart using the data in columns A and B.
The protocols for adding custom error bars differ between Classic Excel and new Excel. After following the appropriate protocol below, the chart will have custom error bars on each data point, based on the additional columns of data. This chart shows just the Y error bars, to show clearly that each point has custom values different from other points:
This chart shows the X and Y error bars:
Important Note
A single custom error bar value cannot be added to a single data point, and custom error bar values cannot be added to a series of data points one point at a time. If you select a single value for your custom error bars, this single value will be applied to all points in the series. A whole set of custom error bar values can be added to an entire series in one operation. Put your custom values into a range parallel to your X and Y values as I’ve done with this sample data, then use the manual technique or the utility to add all the values to the chart series in one step.
New Excel (2007 and later)
It is harder to apply error bars in Excel 2007 than in earlier versions. There is no convenient tab on the Format Series dialog. The Error Bar tab(s) as well as the tabs for Data Label, Up/Down Bars, High/Low Lines, and other features have been removed to make them more discoverable, at least that’s what we were told. To discover these features in Excel 2007, select the chart and navigate to the Chart Tools > Layout contextual tab. Click on the Error Bars button, and scratch your head while you try to decipher the options. Finally, select the More Error Bars Options at the bottom of the list. X (if it’s an XY chart) and Y error bars with initial constant values of 1 are added to the chart series, with the Y error bars selected, and the Format Error Bars dialog is displayed with the Vertical Error Bars tab showing. (If the chart has more than one series, and you had not specifically selected one series, there is an intermediate dialog asking which series to work with.) This dialog doesn’t look too unfamiliar. But there is no obvious way to switch to the horizontal error bars. We are used to having two tabs, one for the vertical error bars, and also one for the horizontal error bars. Remember that Microsoft made these chart formatting dialogs non-modal, so you can click on objects behind the dialogs. Click on the horizontal error bars to change the dialog. To assign custom values to the error bars, select the horizontal or vertical error bars, and on the Horizontal or Vertical Error Bars tab of the Format Error Bars dialog. Move the dialog so it does not cover the range containing your custom values, then click on the Custom option button, and click on Specify Value. A small child dialog appears with entry boxes for selection of the custom error bar values. (It was easier in 2003, where data entry took place directly on the main dialog, but we’re not talking about productivity today.) By default, each field contains a one element array with the element value equal to one. You can enter another constant value, and you don’t need to type the equals sign or curly brackets; Excel will insert them. More likely you want to select a range. Make sure you delete the entire contents of the entry box before selecting a range, or at least select it all, or Excel will think you meant to enter something like the following, which will lead to an error message. The edit box is so narrow, that you cannot see the entire expression at once, and it will be difficult to find this error.
={1}+Sheet1!$D$2:$D$6
If you want the value to be zero, enter zero. Don’t completely clear an entry box, because Excel will think you simply forgot and it will retain the previous value.
Classic Excel (2003 and earlier)
It’s easy to add error bars in Excel 97 through 2003. Bring up the Format Series dialog, by double clicking on the series, by right clicking on the series and choosing Selected Object, by selecting the series and choosing Selected Data Series from the Format menu, or by selecting the series and clicking the shortcut, Ctrl+1 (numeral one). The dialog has a tab for Y Error Bars, and if it’s an XY data series, there is also a tab for X error bars. To define custom error bars, click in the + or – data entry box (no need to select the Custom option button, Classic Excel does this automatically), then select the range containing the custom error bar values using your mouse. If you need only one value for all of the points, you can select a single cell, or even type the value you want. This seems redundant, given the Fixed Value option, but this way you can use different positive and negative fixed values or a custom range for one direction and a constant for the other. This is what the dialog looks like with ranges used to define the custom error bar values. If you want to leave an error bar off the chart, you can leave the data entry box blank.
Notes
The error bars overwhelm the data. To restore the importance of the data itself, use a lighter color for the error bars. Lighten up the axes while you’re at it. If any custom values are negative, the corresponding error bar will be drawn in the opposite direction: a positive error bar with a negative value will be drawn in the negative direction.
Programmatically Defining Custom Error Bars
The command to add error bars using Excel is:
{Series}.ErrorBar Direction:={xlX or xlY}, Include:=xlBoth, Type:=xlCustom, _
Amount:={positive values}, MinusValues:={negative values}
Values can be a single numerical value, for example, 1, an comma-separated array of numerical values in curly braces, such as {1,2,3,4}, or a range address in R1C1 notation. For values in Sheet1!$G$2:$G$10, enter the address as Sheet1!R2C7:R10C7. Combine both plus and minus in the same command. In Excel 2007, if you don’t want to show a particular error bar, you must enter a value of zero in this command. In 2003, you can enter a null string “”. In Excel 2003, the range address must begin with an equals sign, =Sheet1!R2C7:R10C7; Excel 2007 accepts the address with or without the equals sign. Single values or arrays may be entered with or without the equals sign in either version of Excel.
Error Bar Utility
To make it easier to use error bars in Excel 2007 (and in Classic Excel), I’ve built a small utility, which you can download and use for free. It’s found in ErrorBars.zip. This zip file contains two versions, ErrorBars.xls for Excel 97 through 2003, and ErrorBars.xlam for Excel 2007. Install this utility by following the instructions in Installing an Excel Add-In or in Installing an Add-In in Excel 2007. In Classic Excel, the utility places a new item, Add Error Bars, at the bottom of the chart series context menu. All you have to do is right click on the series and select Add Error Bars. Despite all the assurances from Microsoft that context menus work the same in Excel 2007 as in earlier versions, you cannot add an item to an Excel 2007 chart-related context menu. What I’ve done instead is to add an Error Bars item to the end of each of the three Chart Tools contextual ribbon tabs. I know the new philosophy of Office is to place a command in only one place in the whole user interface. I prefer the old style philosophy, however, which is to place the command in every place it may be relevant. I never know where I may be when I want to use a command, and some people remember different hiding places than I do. Whether in Excel 2007 or in earlier versions, click on the added command, and the utility behaves the same. Up pops a simple dialog with four data entry boxes, for plus and minus Y error bars, and for plus and minus X error bars. If the chart type is not XY, the X error bar entry boxes are disabled. You can select a range or enter a constant into the entry boxes. Leave a box blank to omit the corresponding error bars. I hope that this tutorial and the associated utility will make your life easier when working with error bars in Excel 2007.
The geom_errorbar()
function
Error bars give a general idea of how precise a measurement is, or conversely, how far from the reported value the true (error free) value might be. If the value displayed on your barplot is the result of an aggregation (like the mean value of several data points), you may want to display error bars.
To understand how to build it, you first need to understand how to build a basic barplot with R. Then, you just it to add an extra layer using the geom_errorbar()
function.
The function takes at least 3 arguments in its aesthetics:
ymin
andymax
: position of the bottom and the top of the error bar respectivelyx
: position on the X axis
Note: the lower and upper limits of your error bars must be computed before building the chart, and available in a column of the input data.
# Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# Most basic error bar
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
Customization
It is possible to change error bar types thanks to similar function: geom_crossbar()
, geom_linerange()
and geom_pointrange()
. Those functions works basically the same as the most common geom_errorbar()
.
# Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# rectangle
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_crossbar( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
# line
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_linerange( aes(x=name, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# line + dot
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_pointrange( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# horizontal
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3) +
coord_flip()
Standard deviation, Standard error or Confidence Interval?
Three different types of values are commonly used for error bars, sometimes without even specifying which one is used. It is important to understand how they are calculated, since they give very different results (see above). Let’s compute them on a simple vector:
vec=c(1,3,5,9,38,7,2,4,9,19,19)
→ Standard Deviation (SD). wiki
It represents the amount of dispersion of the variable. Calculated as the root square of the variance:
→ Standard Error (SE). wiki
It is the standard deviation of the vector sampling distribution. Calculated as the SD divided by the square root of the sample size. By construction, SE is smaller than SD. With a very big sample size, SE tends toward 0.
→ Confidence Interval (CI). wiki
This interval is defined so that there is a specified probability that a value lies within it. It is calculated as t * SE
. Where t
is the value of the Student???s t-distribution for a specific alpha. Its value is often rounded to 1.96 (its value with a big sample size). If the sample size is huge or the distribution not normal, it is better to calculate the CI using the bootstrap method, however.
After this short introduction, here is how to compute these 3 values for each group of your dataset, and use them as error bars on your barplot. As you can see, the differences can greatly influence your conclusions.
# Load ggplot2
library(ggplot2)
library(dplyr)
# Data
data <- iris %>% select(Species, Sepal.Length)
# Calculates mean, sd, se and IC
my_sum <- data %>%
group_by(Species) %>%
summarise(
n=n(),
mean=mean(Sepal.Length),
sd=sd(Sepal.Length)
) %>%
mutate( se=sd/sqrt(n)) %>%
mutate( ic=se * qt((1-0.05)/2 + .5, n-1))
# Standard deviation
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-sd, ymax=mean+sd), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using standard deviation")
# Standard Error
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-se, ymax=mean+se), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using standard error")
# Confidence Interval
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-ic, ymax=mean+ic), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using confidence interval")
Basic R: use the arrows()
function
It is doable to add error bars with base R only as well, but requires more work. In any case, everything relies on the arrows()
function.
#Let's build a dataset : height of 10 sorgho and poacee sample in 3 environmental conditions (A, B, C)
data <- data.frame(
specie=c(rep("sorgho" , 10) , rep("poacee" , 10) ),
cond_A=rnorm(20,10,4),
cond_B=rnorm(20,8,3),
cond_C=rnorm(20,5,4)
)
#Let's calculate the average value for each condition and each specie with the *aggregate* function
bilan <- aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , mean)
rownames(bilan) <- bilan[,1]
bilan <- as.matrix(bilan[,-1])
#Plot boundaries
lim <- 1.2*max(bilan)
#A function to add arrows on the chart
error.bar <- function(x, y, upper, lower=upper, length=0.1,...){
arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)
}
#Then I calculate the standard deviation for each specie and condition :
stdev <- aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , sd)
rownames(stdev) <- stdev[,1]
stdev <- as.matrix(stdev[,-1]) * 1.96 / 10
#I am ready to add the error bar on the plot using my "error bar" function !
ze_barplot <- barplot(bilan , beside=T , legend.text=T,col=c("blue" , "skyblue") , ylim=c(0,lim) , ylab="height")
error.bar(ze_barplot,bilan, stdev)
What’s next?
This post was an overview of ggplot2 barplots, showing the basic options of geom_barplot()
. Visit the barplot section for more:
- how to reorder your barplot
- how to use variable bar width
- what about error bars
- circular barplots
Bar charts with error bars are useful in engineering to show the confidence or precision in a set of measurements or calculated values. Bar charts without error bars give the illusion that a measured or calculated value is known to high precision or high confidence. In this post, we will build a bar plot using Python and atplotlib. The plot will show the coefficient of thermal expansion (CTE) of three different materials based on a small data set. Then we’ll add error bars to this chart based on the standard deviation of the data.
A bar chart with error bars is shown below. Note the labels on the x-axis and the error bars at the top of each bar.
In order to build this plot, we need a couple of things:
Asset | Description |
---|---|
Python (version 3.6) | Run the program |
Anaconda Prompt | create the virtual environment and install packages |
numpy | calculate the mean and standard deviation |
matplotlib | build the plot |
data set | data to plot |
Before you can build the plot, make sure you have the Anaconda Distribution of Python installed on your computer. See installing Anaconda on Windows for installation instructions.
To get going, we’ll use the Anaconda Prompt to create a new virtual environment. Select Anaconda Prompt from the Windows Start Menu. (If using OSX or Linux, the terminal could also be used)
Once you have the Anaconda Prompt open, type the following command to create a new virtual environment:
conda create -n errorbars
Next, to activate our new (errorbars)
virtual environment, type the following into the Anaconda Prompt
Now that the errorbars virtual environment is active, you should see (errorbars)
in parenthesis before the Anaconda Prompt.
Now we’ll install matplotlib
and numpy
using conda
. (pip will work to install these packages as well) You can write both package names on the same line or use two different conda install
lines.
conda install matplotlib numpy
To confirm our (errorbars)
virtual environment has matplotlib and numpy installed, run the command:
Now let’s create a new Python script called errorbars.py. At the top of the script we need to import numpy
and matplotlib
.
# errorbars.py import numpy as np import matplotlib.pyplot as plt
Next, we need to read in our data. The chart below shows the measured coefficient of thermal expansion (CTE) of three metals: Aluminum, Copper and Steel. The units for coefficient of thermal expansion is per degrees C ( / °C)
Coefficient of thermal expansion of three metals (units: / °C)
Sample | Aluminum | Copper | Steel |
---|---|---|---|
1 | 6.4e-5 | 4.5e-5 | 3.3e-5 |
2 | 3.01e-5 | 1.97e-5 | 1.21e-5 |
3 | 2.36e-5 | 1.6e-5 | 0.9e-5 |
4 | 3.0e-5 | 1.97e-5 | 1.2e-5 |
5 | 7.0e-5 | 4.0e-5 | 1.3e-5 |
6 | 4.5e-5 | 2.4e-5 | 1.6e-5 |
7 | 3.8e-5 | 1.9e-5 | 1.4e-5 |
8 | 4.2e-5 | 2.41e-5 | 1.58e-5 |
9 | 2.62e-5 | 1.85e-5 | 1.32e-5 |
10 | 3.6e-5 | 3.3e-5 | 2.1e-5 |
We’ll put this data into three different numpy arrays, one array for each metal. Notice the syntax np.array([ ... ])
has a parenthesis (
followed by a square bracket [
. We are passing a Python list, [ denoted with square brackets ] into the numpy array function (argument enclosed in parenthesis).
# Enter raw data aluminum = np.array([6.4e-5 , 3.01e-5 , 2.36e-5, 3.0e-5, 7.0e-5, 4.5e-5, 3.8e-5, 4.2e-5, 2.62e-5, 3.6e-5]) copper = np.array([4.5e-5 , 1.97e-5 , 1.6e-5, 1.97e-5, 4.0e-5, 2.4e-5, 1.9e-5, 2.41e-5 , 1.85e-5, 3.3e-5 ]) steel = np.array([3.3e-5 , 1.2e-5 , 0.9e-5, 1.2e-5, 1.3e-5, 1.6e-5, 1.4e-5, 1.58e-5, 1.32e-5 , 2.1e-5])
Now we need to calculate the mean (or average) for each of the three material’s CTE using numpy’s np.mean()
function. The means will be the height of each bar in our chart.
# Calculate the average Aluminum_mean = np.mean(aluminum) Copper_mean = np.mean(copper) Steel_mean = np.mean(steel)
Next we’ll calculate the standard deviation for each metal using numpy’s np.std()
function. On the plot, we will use the standard deviation as the height of our error bars. The positive error will be show as +1 standard deviation above the mean, and the negative error will be shown as -1 standard deviation below the mean.
# Calculate the standard deviation aluminum_std = np.std(aluminum) copper_std = np.std(copper) steel_std = np.std(steel)
There are a couple more things needed to build the plot. We need the names of the metals to go along our x-axis, one name below each bar. We’ll assign the metal names as list of strings in a variable called materials
. We also need a variable that contains the means of the coefficients of thermal expansion, the data we are going to plot. We’ll put these into a Python list called CTEs
. Our standard deviations will be used for the height of the error bars. The standard deviations will go together in a list called error
.
Let’s code all of these Python list into our errorbars.py script.
# Create lists for the plot materials = ['Aluminum', 'Copper', 'Steel'] x_pos = np.arange(len(materials)) CTEs = [aluminum_mean, copper_mean, steel_mean] error = [aluminum_std, copper_std, steel_std]
OK. Now it’s time to build the plot. We are going to build a bar chart with three different bars, one bar for each material: Aluminum, Copper and Steel.
First we will create a figure object called fig
and an axis object in that figure called ax
using matplotlib’s plt.subplots()
function. Everything in our plot will be added to the ax
(axis) object. Next we put a bar chart on our ax
(axis) with the ax.bar()
method.
Note the arguments passed into the ax.bar()
method:
x_pos
is the array with the count of the number of bars.CTEs
is our array which contains the means or heights of the bars.yerr=error
sets the heights of the error bars and the standard deviations.- keyword arguments
(align='center', alpha=0.5, ecolor='black', capsize=10)
styles the plot.
We’ll put a label on the y-axis with the title «Coefficient of thermal expansion (°C-1)» using ax.set_ylabel
. We use ax.set_xticks()
to feed in our number list to set the bars as numbers 1, 2, 3. Then we add labels to these numbered bars with ax.set_ticklabels()
. ax.set_title()
and ax.yaxis.grid(True)
adds a title and horizontal grid lines.
Finally, we we’ll save the figure to a file called bar_plot_with_error_bars.png using matplotlib’s plt.savefig()
function. The plt.thight_layout()
method ensures our axis and labels don’t get cut off and are visible.
# Build the plot fig, ax = plt.subplots() ax.bar(x_pos, CTEs, yerr=error, align='center', alpha=0.5, ecolor='black', capsize=10) ax.set_ylabel('Coefficient of Thermal Expansion ($degree C^{-1}$)') ax.set_xticks(x_pos) ax.set_xticklabels(materials) ax.set_title('Coefficent of Thermal Expansion (CTE) of Three Metals') ax.yaxis.grid(True) # Save the figure and show plt.tight_layout() plt.savefig('bar_plot_with_error_bars.png') plt.show()
The final plot looks like this:
In this Python tutorial, we will discuss Matplotlib plot error bars in python. Here we will cover different examples related to error bars using matplotlib. And we will also cover the following topics:
- Matplotlib plot error bars
- Matplotlib plot error bars example
- Matplotlib interactive plot error bars
- Matplotlib chart error bars
- Matplotlib scatter plot error bars
- Matplotlib plot_date error bars
- Matplotlib plot only error bars
- Matplotlib plot error bars symmetric
- Matplotlib plot error bars asymmetric
- Matplotlib polar plot error bars
In this section, we are going to learn about the error bar. Before starting error bars firstly, we understand what does error means.
Error is a mistake or we can say that difference between the calculated value and actual value.
When we graphical represent the data, some of the data have irregularity. To indicate these irregularities or uncertainties we use Error Bars.
Basically, error bars are used to represent errors in the graphical plot.
The following steps are used to plot error bars in matplotlib which is outlined below:
- Defining Libraries: Import the libraries which are required to plot error bars (For data creation and manipulation: Numpy, For data visualization: pyplot from matplotlib).
- Define X and Y: Define the data values used for plotting. Data values of x-axis and y-axis.
- Plot error bars: By using the errorbar() method we can plot the error bars.
- Display: Finally we have to use the show() method to display the plot.
The syntax to plot error bars is as below:
matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplimes=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, * , data=None, **kwargs)
The above-used parameters are outlined as below:
- x: specifies horizontal coordinates of the data points.
- y: specifies vertical coordinates of the data points.
- xerr: Define the horizontal error bar sizes. Must have a float or array-like shape.
- yerr: Define the vertical error bar sizes. Must have a float or array-like shape.
- fmt: Contains string value. By default, this plot error bars with markers. Use ‘none’ to plot error bars without markers.
- ecolor: specifies the color of the error bars.
- elinewidth: specifies linewidth of the error bars.
- capsize: specifies the length of error bars in points or float.
- capthick: specifies the thickness of error bars cap in float or points.
- barsabove: It contains bool value. By default value is False, if the value is True error bars are plotted above the plot symbol.
- lolims,uplims,xlolims,xuplims: specifies that value gives only upper and lower limits. It contains bool value.
- errorevery: It contains integer values and is used to draw error bars on the subset of the data.
First, learn “How to install matplotlib python“.
Matplotlib plot error bars example
In the above sections, we discussed what does error and error bars mean. And we also discussed what are the various steps used to plot error bars.
Let’s understand the concept with the help of an example as below:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3, 5]
y= [9, 15, 20, 25]
# Plot error bar
plt.errorbar(x, y, xerr = 0.9)
# Display graph
plt.show()
- In the above, example we import the matplotlib.pyplot library.
- Then we define the x-axis and y-axis data points.
- plt.errorbar() method is used to plot error bars and we pass the argument x, y, and xerr and set the value of xerr = 0.9.
- Then we use plt.show() method to display the error bar plotted graph.
Read: Matplotlib plot a line
Matplotlib plot interactive error bars
Here we format the error bars or we can say that customizing the error bar according to our choice to become our error bar more interactive.
Let’s change the following things in the error bars to become it more interactive:
- fmt: change style of marker. Set it to circle.
- color: change the color of the marker. Set it to orange.
- ecolor: change the color of the error bar. Set it to lightgreen.
- elinewidth: change the line width of the error bar. Set it to 5.
- capsize: change the capsize of the error bar. Set it to 10.
Understand the concept with the help of an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3, 5]
y= [9, 15, 20, 25]
# Plot error bar
plt.errorbar(x, y, xerr = 0.9, fmt = 'o',color = 'orange',
ecolor = 'lightgreen', elinewidth = 5, capsize=10)
# Display graph
plt.show()
- In the above example, we plot the error bars and format them according to above mention list.
- We use plt.errorbar() method to plot error bars and become it more interactive.
Read: Python plot multiple lines using Matplotlib
Matplotlib chart error bars
In this section, we will create a chart plot with error bars using Matplotlib. We use plt.errorbar() method to plot error bars in bar charts.
The following are the cases in the bar chart in which we draw error bars:
- Error in x values
- Error in y values
- Error in both x and y values
Matplotlib chart error bars in x values
By using the plt.errorbar() method we plot the error bars and pass the argument xerr to plot error on the x values.
The syntax for this is:
matplotlib.pyplot.errorbar(x, y, xerr=None)
Let’s understand this concept with the help of an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [6, 15, 2.3, 9]
y= [9, 15, 20, 25]
# Define Error
x_error = [2.3, 5.1, 1, 3.1]
# Plot Bar chart
plt.bar(x,y)
# Plot error bar
plt.errorbar(x, y, xerr = x_error,fmt='o',ecolor = 'red',color='yellow')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library and define the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.bar() method to plot a bar chart.
- plt.errorbar() method is used to plot error bars and we pass xerr as an argument and set its value to be x_error value which we define.
Matplotlib chart error bars in y values
By using the plt.errorbar() method we plot the error bars and pass the argument yerr to plot error on the y values.
The syntax to plot error bars on y values is as given below:
matplotlib.pyplot.errorbar(x, y, yerr=None)
Let’s take an example for better understanding:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [6, 15, 2.3, 9]
y= [9, 15, 20, 25]
# Define Error
y_error = [2.3, 5.1, 1, 3.1]
# Plot Bar chart
plt.bar(x,y)
# Plot error bar
plt.errorbar(x, y, yerr = y_error,fmt='o',ecolor = 'red',color='yellow')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.bar() method to plot a bar chart and use plt.errorbar() method is used to plot error bars.
- Pass yerr as an argument and set its value to equal y_error value which we define.
Matplotlib chart error bars in x and y values
By using the plt.errorbar() method we plot the error bars and pass the argument xeer and yerr to plot error on both x and y values respectively.
The syntax to plot error bars on both the values is as given below:
matplotlib.pyplot.errorbar(x, y, xerr=None, yerr=None)
Let’s take an example to know how to plot errorbars on both values:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [6, 15, 2.3, 9]
y= [9, 15, 20, 25]
# Define Error
x_error = [4.2, 6, 10, 8.6]
y_error = [2.3, 5.1, 1, 3.1]
# Plot Bar chart
plt.bar(x,y)
# Plot error bar
plt.errorbar(x, y, xerr = x_error, yerr = y_error,
fmt='o', ecolor = 'red',color='yellow')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.bar() method to plot a bar chart and use plt.errorbar() method is used to plot error bars.
- Pass xeer, yerr as an argument and set its value to equal x_error, y_error value respectively which we define.
Read: What is matplotlib inline
Matplotlib scatter plot error bars
In this section, we will create a scatter plot with error bars using Matplotlib. We use plt.errorbar() method to plot error bars in scatter plot.
The following are the cases in the scatter plot in which we draw error bars:
- Error in x values
- Error in y values
- Error in both x and y values
Matplotlib scatter plot error bars in x values
By using the plt.errorbar() method we plot the error bars and pass the argument xerr to plot error on the x values in the scatter plot.
The syntax for this is:
matplotlib.pyplot.errorbar(x, y, xerr=None)
Let’s understand this concept with the help of an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]
# Define Error
x_error = [2, 4, 6, 8]
# Plot scatter plot
plt.scatter(x,y)
# Plot error bar
plt.errorbar(x, y, xerr = x_error,fmt='o',ecolor = 'cyan',color='black')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library and define the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.scatter() method to draw a scatter plot.
- plt.errorbar() method is used to plot error bars and we pass xerr as an argument and set its value to be x_error value which we define.
Matplotlib scatter plot error bars in y values
By using the plt.errorbar() method we plot the error bars and pass the argument yerr to plot error on the y values in the scatter plot.
The syntax to plot error bars on y values is as given below:
matplotlib.pyplot.errorbar(x, y, yerr=None)
Let’s take an example for better understanding:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]
# Define Error
y_error = [2, 4, 6, 8]
# Plot Scatter Plot
plt.scatter(x,y)
# Plot error bar
plt.errorbar(x, y, yerr = y_error,fmt='o',ecolor = 'cyan',color='black')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.scatter() method to plot a scatter plot and use plt.errorbar() method is used to plot error bars.
- Pass yerr as an argument and set its value to equal y_error value which we define.
Matplotlib scatter plot error bars in x and y values
By using the plt.errorbar() method we plot the error bars and pass the argument xeer and yerr to plot error on both x and y values respectively.
The syntax to plot error bars on both the values is as given below:
matplotlib.pyplot.errorbar(x, y, xerr=None, yerr=None)
Let’s take an example to know how to plot errorbars on both values:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]
# Define Error
x_error= [3, 6, 9, 12]
y_error = [2, 4, 6, 8]
# Plot Scatter Plot
plt.scatter(x,y)
#Plot error bar
plt.errorbar(x, y, xerr= x_error, yerr = y_error,fmt='o',ecolor = 'cyan',color='black')
# Display graph
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.scatter() method to plot a scatter plot and use plt.errorbar() method is used to plot error bars.
- Pass xeer, yerr as an argument and set its value to equal x_error, y_error value which we define.
Read: Matplotlib plot bar chart
Matplotlib plot_date error bars
In this section, we will create a dates plot with error bars using Matplotlib. We use plt.errorbar() method to plot error bars.
The following are the cases in the dates plot in which we draw error bars:
- Error in x values
- Error in y values
- Error in both x and y values
Matplotlib plot_date error bars in x values
By using the plt.errorbar() method we plot the error bars and pass the argument xerr to plot error on the x values in the date plot.
The syntax for this is:
matplotlib.pyplot.errorbar(x, y, xerr=None)
Let’s understand this concept with the help of an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3]
y= [1.5, 2, 2.5]
# Define Error
x_error= 1.5
# Plot Date
plt.plot_date(x,y)
#Plot error bar
plt.errorbar(x, y, xerr= x_error, fmt='o',
ecolor = 'lightblue',color='m')
# Display graph
plt.tight_layout()
plt.show()
- In the above example, we import matplotlib.pyplot library and define the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.plot_date() method to draw a plot consisting dates.
- plt.errorbar() method is used to plot error bars and we pass xerr as an argument and set its value to be x_error value which we define.
Read: Matplotlib subplot tutorial
Matplotlib plot_date error bars in y values
By using the plt.errorbar() method, we plot the error bars and pass the argument yerr to plot the error on the y values in the date plot.
The syntax to plot error bars on y values is as given below:
matplotlib.pyplot.errorbar(x, y, yerr=None)
Let’s take an example for better understanding:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3]
y= [0.5, 0.8, 1]
# Define Error
y_error= 0.1
# Plot Date
plt.plot_date(x,y)
# Plot error bar
plt.errorbar(x, y, yerr= y_error, fmt='o',
ecolor = 'lightblue',color='m')
# Display graph
plt.tick_params(axis='x', which='major', labelsize=8)
plt.tight_layout()
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.plot_date() method to plot a graph consisting of dates and use plt.errorbar() method is used to plot error bars.
- Pass yerr as an argument and set its value to equal y_error value which we define.
Matplotlib plot_date error bars in x and y values
By using the plt.errorbar() method we plot the error bars and pass the argument xeer and yerr to plot error on both x and y values respectively in the date plot.
The syntax to plot error bars on both the values is as given below:
matplotlib.pyplot.errorbar(x, y, xerr=None, yerr=None)
Let’s take an example to know how to plot errorbars on both valuesin date plot:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1,2,3]
y= [1.5, 2, 2.5]
# Define Error
x_error= 1.5
y_error = 2.3
# Plot Date
plt.plot_date(x,y)
# Plot error bar
plt.errorbar(x, y, xerr= x_error, yerr = y_error,fmt='o',ecolor = 'lightblue',color='m')
# Display graph
plt.tight_layout()
plt.show()
- In the above example, we import matplotlib.pyplot library
- After this defines the data point on the x-axis and y-axis.
- Then we define the error value and use the plt.plot_date() method to plot a dates and use plt.errorbar() method is used to plot error bars.
- Pass xeer, yerr as an argument and set its value to equal x_error, y_error value which we define.
Read: Matplotlib best fit line
Matplotlib plot only error bars
Here we learn about how we can plot error bars only.
The syntax to plot error bars is:
matplotlib.pyplot.errorbar(x,y,xerr=None,yerr=None)
The parameters used above are:
- x: horizontal coordinates of the data points.
- y: vertical coordinates of the data points.
- xerr: Define the horizontal error bar sizes. Must have a float or array-like shape.
- yerr: Define the vertical error bar sizes. Must have a float or array-like shape.
Let’s take an example to create only error bars:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3]
y= [1.5, 2, 2.5]
# Define Error
x_error = 0.2
y_error = 0.5
#Plot error bar
plt.errorbar(x, y, xerr= x_error, yerr = y_error,fmt='o',
ecolor = 'pink',color='blue')
# Display graph
plt.show()
In the above example, we define the data and error values, and by using the errorbar() method we plot the only error bar graph.
Read: Matplotlib subplots_adjust
Matplotlib plot error bars symmetric
Here we learn what does symmetric error bars are. Errors are constant values and we represent the error values in the array form.
Sometimes, we have a case in which an error differed for each point, but the lower and upper values of error are equal. That type of case is known as the symmetric error bar.
In the symmetric case, the shape of an array is in the form: (N,)
Let’s see the example of symmetric error bars:
# Import library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.arange(2, 16, 1.5)
y = np.exp(x*2)
# Define Data
error = 0.1 * x
# Plot error
plt.errorbar(x, y, yerr=error, fmt='-o')
# Display Graph
plt.show()
- In the above example, we define data using NumPy arrange() method and exp() method. After that, we define error value in the shape of (N,).
- By using plt.errorbar() method, we plot the symmetric error bars.
Read: Matplotlib log log plot
Matplotlib plot error bars asymmetric
Here we learn what does asymmetric error bars are. Errors are constant values and they are represented in the array form.
Sometimes, we have a case in which an error differed for each point, but the lower and upper limits of error are unequal or different in nature. That type of case is known as the asymmetric error bar.
In the asymmetric case, the shape of an array is in the form: (2, N).
Let’s see the example of asymmetric error bars:
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.arange(2, 16, 1.5)
y = np.exp(x*2)
# Define errors
error = 0.1 * x
# Lower limit of error
lower_error = 0.6 * error
# Upper limit of error
upper_error = error
# plot error bars
asymmetric_error = [lower_error, upper_error]
plt.errorbar(x, y, xerr=asymmetric_error, fmt='o')
# Display Graph
plt.show()
In the above example, we define different values of error of lower and upper limits. By using the plt.errorbar() method we plot error bars in asymmetric nature.
Read: Matplotlib plot_date
Matplotlib polar plot error bars
A Cartesian coordinate system is plotted using the polar coordinates. plt.polar() method is used to plot the polar coordinates.
The syntax to plot polar plot is as given below:
matplotlib.pyplot.polar(r, theta)
The parameter used above are:
- r: specifies the distance from the origin.
- theta: Specifies the angle at which distance from the origin has to be measured.
Let’s see an example of plotting error bars in polar coordinates:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
r= np.arange(0, 4, 0.5)
theta= 2*np.pi*r
# Define Error
x_error = 0.2
y_error = 5
# Plot polar coordinates
plt.polar(r,theta,"ro")
# Plot error bar
plt.errorbar(r, theta, xerr = x_error, yerr= y_error, color='black')
# Display graph
plt.show()
- In the above example, we import matplotlib and numpy library.
- After that, we define ‘r’ and ‘theta‘ i.e distance and angle.
- Then we plot the polar coordinates by using the plt.polar() method and by using the plt.errorbar() method we plot error bars in the polar plot.
- Finally, we display plt.show() method to display the polar plot.
You may also like to read the following Matplotlib tutorials.
- Matplotlib dashed line
- Matplotlib scatter marker
- Matplotlib change background color
- Matplotlib rotate tick labels
- Matplotlib remove tick labels
In this Python tutorial, we have discussed the “Matplotlib plot error bars” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Matplotlib plot error bars
- Matplotlib plot error bars example
- Matplotlib interactive plot error bars
- Matplotlib chart error bars
- Matplotlib scatter plot error bars
- Matplotlib plot_date error bars
- Matplotlib plot only error bars
- Matplotlib plot error bars symmetric
- Matplotlib plot error bars asymmetric
- Matplotlib polar plot error bars
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Basic Symmetric Error Bars
var data = [
{
x: [0, 1, 2],
y: [6, 10, 2],
error_y: {
type: 'data',
array: [1, 2, 3],
visible: true
},
type: 'scatter'
}
];
Plotly.newPlot('myDiv', data);
Bar Chart with Error Bars
var trace1 = {
x: ['Trial 1', 'Trial 2', 'Trial 3'],
y: [3, 6, 4],
name: 'Control',
error_y: {
type: 'data',
array: [1, 0.5, 1.5],
visible: true
},
type: 'bar'
};
var trace2 = {
x: ['Trial 1', 'Trial 2', 'Trial 3'],
y: [4, 7, 3],
name: 'Experimental',
error_y: {
type: 'data',
array: [0.5, 1, 2],
visible: true
},
type: 'bar'
};
var data = [trace1, trace2];
var layout = {barmode: 'group'};
Plotly.newPlot('myDiv', data, layout);
Horizontal Error Bars
var data = [
{
x: [1, 2, 3, 4],
y: [2, 1, 3, 4],
error_x: {
type: 'percent',
value: 10
},
type: 'scatter'
}
];
Plotly.newPlot('myDiv', data);
Asymmetric Error Bars
var data = [
{
x: [1, 2, 3, 4],
y: [2, 1, 3, 4],
error_y: {
type: 'data',
symmetric: false,
array: [0.1, 0.2, 0.1, 0.1],
arrayminus: [0.2, 0.4, 1, 0.2]
},
type: 'scatter'
}
];
Plotly.newPlot('myDiv', data);
Colored and Styled Error Bars
function linspace(a,b,n) {
return d3.range(n).map(function(i){return a+i*(b-a)/(n-1);});
}
x_theo = linspace(-4, 4, 100)
sincx = Math.sin(x_theo) / x_theo
var x = [-3.8, -3.03, -1.91, -1.46, -0.89, -0.24, -0.0, 0.41, 0.89, 1.01, 1.91, 2.28, 2.79, 3.56]
var y = [-0.02, 0.04, -0.01, -0.27, 0.36, 0.75, 1.03, 0.65, 0.28, 0.02, -0.11, 0.16, 0.04, -0.15]
var trace1 = {
x: x_theo,
y: sincx,
name: 'sinc(x)',
type: 'scatter'
};
var trace2 = {
x: x,
y: y,
mode: 'markers',
name: 'measured',
error_y: {
type: 'constant',
value: 0.1,
color: '#85144B',
thickness: 1.5,
width: 3,
opacity: 1
},
error_x: {
type: 'constant',
value: 0.2,
color: '#85144B',
thickness: 1.5,
width: 3,
opacity: 1
},
marker: {
color: '#85144B',
size: 8
},
type: 'scatter'
};
var data = [trace1, trace2];
Plotly.newPlot('myDiv', data, {}, {showSendToCloud: true});
Error Bars as a Percentage of the y-Value
var data = [
{
x: [0, 1, 2],
y: [6, 10, 2],
error_y: {
type: 'percent',
value: 50,
visible: true
},
type: 'scatter'
}
];
Plotly.newPlot('myDiv', data);
Asymmetric Error Bars with a Constant Offset
var data = [
{
x: [1, 2, 3, 4],
y: [2, 1, 3, 4],
error_y: {
type: 'percent',
symmetric: false,
value: 15,
valueminus: 25
},
type: 'scatter'
}
];
Plotly.newPlot('myDiv', data);
Categories: Advanced Excel
Tags: Standard Deviation Excel Graph
It would be nice if all data was perfect, absolute and complete. But when it isn’t, Excel gives us some useful tools to convey margins of error and standard deviations. If you work in a field that needs to reflect an accurate range of data error, then follow the steps below to add Error Bars to your charts and graphs:
Begin by creating your spreadsheet and generating the chart or graph you will be working with.
To follow using our example below, download Standard Deviation Excel Graphs Template1 and use Sheet 1. These steps will apply to Excel 2013. Images were taken using Excel 2013 on the Windows 7 OS.
Click on the chart, then click the Chart Elements Button to open the fly-out list of checkboxes. Put a check in the Error Bars checkbox.
Click the arrow beside the Error Bars checkbox to choose from common error types:
- Standard Error – Displays standard error amount for all values.
- Percentage – Specify a percentage error range and Excel will calculate the error amount for each value. Default percentage is 5%.
- Standard Deviation – Displays standard deviation error amount for all values. Resulting X &Y error bars will be the same size and won’t vary with each value.
You can also turn on Error bars from the Add Chart Element dropdown button on the Design tab under the Chart Tools contextual tab.
SAVE $10 AND TRAIN ON THIS TOPIC TODAY
Blast from the Past: Error Bars function similarly in Excel 2007-2010, but their location in the user interface changed in 2013. To find and turn on Error Bars in Excel 2007-2010, select the chart, then click the Error Bars dropdown menu in the Layout tab under the Chart Tools contextual tab.
Customize Error Bar Settings
To customize your Error Bar settings, click More Options to open the Format Error Bars Task Pane.
To follow using our example, download the Standard Deviation Excel Graphs Template1 and use Sheet 2.
From here you can choose to:
- Set your error bar to appear above the data point, below it, or both.
- Choose the style of the error bar.
- Choose and customize the type and amount of the error range. Select the type of error calculation you want, then enter your custom value for that type.
Bar chart showing error bars with custom Percentage error amount.
Line chart showing error bars with Standard deviation(s) of 1.3
If you need to specify your own error formula, select Custom and then click the Specify Value button to open the Custom Error Bars dialog box. In the dialog box you can enter an absolute value or a formula to treat all data points equally. Or, you can enter a cell range that contains an Error result that you need for each individual data point.
In this over-simplified example, we selected B4:E4 cell range for both positive and negative error values. These cells contain a formula that calculates the error value based on a margin of error that is unique to each type of bird species. The resulting error bars, then, are also unique to each bar in the chart.
The addition of error bars can help the statistician or researcher, or anyone working with complex data, convey their information with visual impact and clarity.
PRYOR+ 7-DAYS OF FREE TRAINING
Courses in Customer Service, Excel, HR, Leadership,
OSHA and more. No credit card. No commitment. Individuals and teams.