# How to create a graph with shaded region in Tikz

I am looking to create the graph for the function y = 1/x for x > 0. The area under the curve between x = a and x = 1 is A1. The area under the curve between x = 1 and x = b is A2.

I don't know how to shade the regions as shown in the figure.

• Could you please add the code to reproduce your graph (without the shading, of course, we will add it)? – CarLaTeX Jun 8 at 5:58

## 1 Answer

Most of this is from the example on the bottom of p. 103 of the manual, and the positioning of x and y is from this answer.

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.16,width=10cm}
\begin{document}
\begin{tikzpicture}[declare function={a=0.5;b=3;f(\x)=1/\x;}]
\begin{axis}[axis lines=middle,axis on top,xlabel=$x$,ylabel=$y$,
xmin=-0.5,xmax=5,ymin=-0.5,ymax=2,ytick=\empty,
xtick={a,1,b},xticklabels={$a$,$1$,$b$}, % https://tex.stackexchange.com/a/68407/121799
every axis x label/.style={at={(current axis.right of origin)},anchor=north west},
every axis y label/.style={at={(current axis.above origin)},anchor=north east}]
\addplot[name path=A,blue,thick,domain=0.2:5,smooth] {f(x)};
\path[name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0);
\addplot [gray!30] fill between [
of=A and B,soft clip={domain=a:1},
];
\addplot [gray] fill between [
of=A and B,soft clip={domain=1:b},
];
\path ({(1+a)/2},{f((1+a)/2)/2}) node{$A_1$}
({(1+b)/2},{f((1+b)/2)/2}) node{$A_2$};
\end{axis}
\end{tikzpicture}
\end{document}