Why have certain plants evolved to contain psychoactive compounds?
The evolutionary history of different plants expressing psychoactive compounds can vary, and in many cases it's difficult if not impossible to pinpoint a particular origin. However, we can make some general observations:

Homology across wide ranges of species

Despite the differences between, say, a human versus a locust, animals share a lot of their physiology. Mammals and insects tend to use different neurotransmitters for different purposes, for example, but the actual neurotransmitters and their receptors are often homologous. A plant could therefore develop a compound that acts as a neurotoxin in certain insects, but also has some psychoactive effects in a human. Nicotine is an example of a psychoactive compound that has insecticidal effects: not only does nicotine protect a tobacco plant, but humans have even used nicotine as an insecticide. Plants could of course also develop toxins to protect them from other mammals, and those would be even more likely to have effects in humans.

There is even homology across kingdoms, such that plants could make compounds to prevent growth of competing plants, act as antibiotics/antifungals, etc, and all have a possibility to act on some homologous proteins that humans have.

Artificial selection

Once humans are aware of a plant's psychoactive or other medicinal properties, that plant can be cultivated and selected for desirable properties. In the case of a compound like THC, there is good evidence that this has occurred recently. In the case of plants that produce opiate compounds, many have been cultivated by humans for thousands of years, so they are a lot more prevalent than they would be if humans had not chosen to do so.

Selection bias

Maybe I should have opened with this one, because I think it's very very important to be aware of. I'm not talking about selection in evolutionary terms here, but in terms of cognitive biases. Selection bias happens when you focus on certain outcomes and not others. There are innumerable compounds produced by plants that can potentially have some biological activity in humans: thousands and thousands. Some do have psychoactive effects, others have effects on other body systems, and many have little effect at all besides dietary contributions. You notice all of the plants that do produce something "interesting" but ignore those that are benign or simply toxic.