It turns out that this is determined by the chemicals they contain. Sweet plants, such as fruits and some vegetables, contain many sugars, such as sucrose, glucose, maltose, fructose, etc. Although some plants are not sweet, they contain a lot of starch. When they are eaten in the mouth, when starch is combined with saliva, it will decompose to produce glucose and maltose, so it will be sweet.
Some plants have sour taste because they contain acids, such as citric acid, tartaric acid, acetic acid, oxalic acid and so on.
The astringent taste is because plants contain a lot of tannic acid, such as persimmons, olives and tea.
Those bitter Chinese medicines and other bitter plants all contain some alkaloids, such as berberine and cinchona in Coptis chinensis.
The formation of spicy taste is complicated, for example, mustard oil in radish is different from nicotine and capsaicin in tobacco.