Pencils are yellow because yellow meant "the best". That's the short version. The story behind it comes in a couple of versions of its own.
Here's how it's usually told. In the 1890s, pencil makers began painting their top-quality pencils yellow. The finest graphite was linked with China, where yellow was the colour of royalty. So a yellow pencil was a way of saying "this one is the good stuff".
The writer Henry Petroski gives a slightly different version. In 1890 the L. and C. Hardtmuth company of Austria-Hungary brought out its Koh-I-Noor pencil, named after the famous diamond. It was meant to be the best and most expensive pencil in the world. At a time when most pencils were painted dark colours or not painted at all, the Koh-I-Noor was yellow. Yellow was on the Austro-Hungarian flag. It also hinted at the East, at a time when the best graphite came from Siberia.
Here's the weird part. In both versions, the colour has nothing to do with how the pencil writes. It was all about looking like the best.
And it worked. Other makers wanted their pencils to be linked with the high-quality ones, so they copied the yellow paint. Some even chose names with eastern links, such as Mikado. Today the majority of pencils made in the United States are still painted yellow.
So when you pick up a yellow pencil, you're holding a little bit of marketing from the 1890s. The paint has been quietly saying "the best" ever since.