In general, flower color is due to two different pigments - flavonoids, and carotenoids. The carotenoid pigments are located within chromoplasts (* term defined below) which are found in the cytoplasm (*).
These pigments are responsible for yellow through orange colors. The flavonoid pigments, unlike the other two pigments, are located within the cellular vacuole (*) and are responsible for red through blue colors.
Flower color is the result of mixing the two pigments in different proportions. By mixing and matching these pigments, a wide array of different colors can be created. For example, the red color of in several plants is the result of mixing orange carotenoids with magenta flavonoids.
Most flowers do not contain carotenoid pigments. The only pigments present are flavonoids. These flavonoids can be artificially subdivided into two groups - the anthocyanins and the co-pigments. At physiological pHs (acidity level) of the cell, the anthocyanins are not very stable and are nearly colorless. The addition of co-pigments to the anthocyanins increases both the stability and intensity of the anthocyanin's color.
This effect is called co-pigmentation.
Chemical interactions between the molecular structure of the anthocyanin and co-pigment result in visible color. It is generally assumed that red flowers contain predominantly cyanidin (anthocyanin) and blue flowers mostly delphinidin (anthocyanin). Although this is usually true, there are many exceptions. For example, flowers that contain cyanidin can either be red as in rose or blue as in corn flower.
One of the major reasons why flowers containing the same anthocyanin can be different colors is the cellular pH. As the pH becomes more alkaline, the color of a specific anthocyanin/co-pigment complex becomes more blue. The pH of the soil has little or no effect on the pH of the flower cells. The pH of the flower is genetically regulated.
As to the second part of your question on the "why" of flower coloring.... Perhaps the best-known, or handiest explanation, Griesbach agrees, is to attract helpful insects like bees that spread pollen around as they busily fly from flower to flower. And by producing lush, tasty, colorful fruit, plants can also whet the appetite of helpful animals such as birds to disperse seed (through excretion) over great distances.
* cytoplasm: jelly-like substance surrounding the nucleus of a cell.
* chromoplast: a tiny compartment or structure in plant cells that stores pigments, such as caretenoid, for example.
* vacuole: pockets or spaces in the jelly-like cytoplasm. In plants, there is one large vacuole, according to the Concise Science Dictionary, and several such spaces in the cytoplasm of animal cells. In plants, it may help to think of vacuoles and chromoplasts as two kinds of storage areas.
Source: Agricultural Research Service