Coordinate systems/Derivation of formulas/Spherical from Cartesian unit vectors

From Wolfram Mathworld, we have the following relations for the unit vectors in a Spherical coordinate system:

$$\begin{align}

\hat{\mathbf r}&=\cos\phi\sin\theta\hat{\mathbf x}+\sin\phi\sin\theta\hat{\mathbf y}+\cos\theta\hat{\mathbf z} \\ \hat{\boldsymbol\theta}&=\cos\phi\cos\theta\hat{\mathbf x}+\sin\phi\cos\theta\hat{\mathbf y}-\sin\theta\hat{\mathbf z} \\ \hat{\boldsymbol\phi}&=-\sin\phi\hat{\mathbf x}+\cos\phi\hat{\mathbf y} \end{align}$$

Next, we need to change all the $$\phi$$ and $$\theta$$ to $$x,y,z$$. We use the following relations, also available on the same page :

$$\begin{align} r&=\sqrt{x^2+y^2+z^2} \\ \theta&=\arccos(\frac{z}{r}) \\ \phi&=\arctan(\frac{y}{x}) \end{align}$$

Using these, we can find the following quantities:

$$\begin{align} \cos\theta&=\frac{z}{r}=\frac{z}{\sqrt{x^2+y^2+z^2}} \\ \sin\theta&=\sqrt{1-\cos^2\theta}=\sqrt{1-\frac{z^2}{x^2+y^2+z^2}}=\sqrt{\frac{x^2+y^2}{x^2+y^2+z^2}} \\ \cos\phi&=\frac{x}{\sqrt{x^2+y^2}} \\ \sin\phi&=\frac{y}{\sqrt{x^2+y^2}} \end{align}$$

Lastly, we simply need to substitute these relations into our first set of equations to obtain our desired result:

$$\begin{align} \hat{\mathbf r}&=\frac{x}{\sqrt{x^2+y^2}}\sqrt{\frac{x^2+y^2}{x^2+y^2+z^2}}\hat{\mathbf x}+\frac{y}{\sqrt{x^2+y^2}}\sqrt{\frac{x^2+y^2}{x^2+y^2+z^2}}\hat{\mathbf y}+\frac{z}{\sqrt{x^2+y^2+z^2}}\hat{\mathbf z}=\frac{x \hat{\mathbf x} + y \hat{\mathbf y} + z \hat{\mathbf z}}{\sqrt{x^2+y^2+z^2}}\\

\hat{\boldsymbol\theta}&=\frac{x}{\sqrt{x^2+y^2}}\frac{z}{\sqrt{x^2+y^2+z^2}}\hat{\mathbf x}+\frac{y}{\sqrt{x^2+y^2}}\frac{z}{\sqrt{x^2+y^2+z^2}}\hat{\mathbf y}-\sqrt{\frac{x^2+y^2}{x^2+y^2+z^2}}\hat{\mathbf z}=\frac{x z \hat{\mathbf x} + y z \hat{\mathbf y} - \left(x^2 + y^2\right) \hat{\mathbf z}}{\sqrt{x^2+y^2} \sqrt{x^2+y^2+z^2}} \\

\hat{\boldsymbol\phi}&=-\frac{y}{\sqrt{x^2+y^2}}\hat{\mathbf x}+\frac{x}{\sqrt{x^2+y^2}}\hat{\mathbf y}=\frac{- y \hat{\mathbf x} + x \hat{\mathbf y}}{\sqrt{x^2+y^2}} \end{align}$$