The team of color scientists hovered in their white coats and hairnets, staring down at a clear plastic box full of strangely colored M&Ms. “They look like pebbles, ugly little pebbles,” said Rebecca Robbins, the color-chemistry manager for Mars Chocolate. She propped open the lid to show off a muted array of gray, tan, mauve, pale purple and sickly pink chocolate nuggets. Each attenuated shade was the disappointing outcome of an early attempt by Mars to replace a bright, artificial dye with natural pigments extracted from algae, roots, seeds and other parts of plants. Not a single piece of candy in this tackle box of failure looked edible — let alone tempting.

Noticeably absent was any M&M that even vaguely resembled blue, the most coveted, and hardest to find, of colors. Blue is a rarity among plants and animals. When it does occur in nature, it often isn’t truly blue, but rather a trick of diffraction, or the scattering of light, which is the case for bird feathers, sky, ice, water and iridescent butterfly wings. A blueberry is actually more red than blue when you mash it. “Unfortunately, you can’t just grind up a peacock feather,” said Robbins, a petite woman with a Ph.D. in organic chemistry and the empathic, wide-set blue eyes of a small-town bartender, with what sounded like genuine regret.

The Mars research kitchen lacks many of the familiar accouterments of a home kitchen and is really more of a laboratory. Located at the North American headquarters of Mars Chocolate in Hackettstown, N.J., it adjoins a huge manufacturing facility that makes half the country’s M&M supply; when I visited at the end of July, the place was already months into its pre-Halloween production frenzy. In response to growing pressure from consumers across the globe, Mars announced in February that over the next five years it would remove artificial colors from all the processed foods it makes for human consumption, and that pigments found in natural substances would take their place. This research kitchen is where scientists are now cautiously tinkering with the chemistry of some of America’s most celebrated candies.

Mars has joined a growing list of global food manufacturers removing artificial dyes from some or all of their products. The companies include Nestlé USA, General Mills, Kraft, Frito-Lay, Campbell’s, Kellogg’s and Mondelez International (the maker of Oreos, Tang and Sour Patch Kids). The orange glow of Kraft’s revamped macaroni and cheese now comes from paprika, turmeric and annatto, a coloring extracted from tree seeds. General Mills experimented with 69 different natural dyes before it released a naturally colored Trix and six other reconfigured cereals in January. (The company was unable to find a workable blue or green, so those colors have been left out for now.)

In 2013, the Food and Drug Administration approved Mars’s petition to use the microscopic algae spirulina to make the first natural blue dye approved for use in the United States. As a result, any food manufacturer in the country can legally use spirulina as a colorant. Mars spent years researching spirulina’s safety; in order to overhaul 1,700 or so recipes and update its global manufacturing capabilities, the company desperately needs a substitute for synthetic Blue No. 1, as does the rest of the industry. But right now, there isn’t nearly enough spirulina dye to go around — and in any case, sometimes it doesn’t yield just the right blue, or the color degrades and comes out blotchy, or it tastes odd. So researchers are still looking everywhere for other natural blue pigments. Among the contenders being tested in laboratories are a berry found in Central and South America, the huito, traditionally used to make dark blue, semi-permanent ceremonial tattoos and as a bug repellent; a blue gardenia flower; red cabbage; aged red wine; a bacteria used to make Swiss cheese; the Japanese kusagi berry; butterfly-pea flowers; and pigments derived from soil bacteria, tree-root fungi, sea sponges and mushrooms. With funding from PepsiCo, another business expanding its use of natural colors, a University of Illinois grad student in pharmacognosy (the study of medicinal substances found in nature), who has spent several years searching for new blues, recently found a previously unknown blue pigment in algae growing in a hot spring in Yellowstone National Park.

Many colors have well-established natural-dye alternatives: orange from beta-carotene, for example, or yellow from turmeric, a mainstay in curry. Robbins has spent seven years studying the molecular structures of these dyes, and here’s what she has learned: Natural compounds are unpredictable. The molecules hold on to remnants of the places where they grew — the minerals in the water, say, or the weather during a growing season — and sometimes those earthy, atmospheric residues look strange or taste and smell funky. Artificial colors are simple, stable and nonreactive; Robbins calls them “happy campers.” Yellow No. 5 looks the same whether it’s in an acidic product (a Skittle, for instance) or a more basic one (an M&M), while acidic conditions can change a natural pigment from pink to dark blue.

On the day I saw her kitchen, Robbins was preparing to produce a test batch of M&Ms colored blue using pigment from red cabbage. The smell of warm chocolate was tinged with a faint, sulfuric sauerkraut smell. Despite the sterile setting, earthy odor molecules from natural dyes somehow made their presence known — a borscht aroma from the beet dye, a slight eggy scent from the radish. Over the last century, the processed-food industry largely succeeded in replacing fickle nature with synthetic, shelf-stable colors and flavors and preservatives concocted in laboratories. Now that work has to be undone. As Neil Willcocks, vice president of global research and development for the Wrigley division of Mars, told me, “This is the most complex technical undertaking that any of us have ever seen in the history of the company.”

Scientists estimate that more than half the human brain is involved in processing what we see. Only about 1 percent or so is dedicated to taste. Within the first few months of life, babies begin to distinguish among colors, showing a preference for more saturated ones, especially blues and reds. Vision overwhelms the other senses. If researchers want you to really taste something, feel its texture against your tongue and smell its subtle notes, they will make you eat it in the dark or under lights that mask colors. Humans are color-seeking animals, and food companies learned to manipulate that trait early.

In the early 1800s, just as chemistry emerged as a real science from the murky realm of alchemy, food sellers increasingly began to add things to their products, usually to hide discoloration or spoilage. Copper made pallid pickles green again; children ate candies turned red with lead; old milk was watered down, dyed yellow and thickened with flour and other dubious powders. Sometimes these colorants and heavy metals killed people directly, but more often — in milk, for example — they simply concealed the presence of contaminants or bacteria that caused illness and death.

In 1906, Congress passed the Food and Drugs Act, which banned poisonous colors. Most of the approved dyes were derived from aromatic hydrocarbons found in the thick black liquid left over from processing coal for fuel. A young British chemist stumbled on mauve, the first coal-tar dye, while trying to distill artificial quinine in 1856. Six years later, a New York Times article hailing the role played by the new dyes in textile production noted how fortuitous the discovery was for coal manufacturers. Before mauve and other so-called coal-tar dyes became the basic ingredients in this new synthetic-color industry, coal companies were repeatedly prosecuted for polluting waterways with what The Times referred to as “singularly repulsive refuse.” These coal-tar colors revolutionized fashion, medicine and food, becoming essential components in cereals, snacks and candy. In 1941, Mars made the first M&Ms, which were included in American soldiers’ rations, by coating heat-resistant, transportable chocolates with coal-tar colors and stamping them with a lowercase “M.”

The potential dark side of these garish colors began to emerge on Halloween in 1950. Dozens of trick-or-treating children, in a couple of cities, became ill after eating candy tinted with high levels of Orange No. 1, then one of the most widely used coal-tar additives found in soft drinks, candy, baked goods and processed meats like hot dogs. Government officials collected candy samples and sent them to Washington, where volunteers who ate them became sick with diarrhea and abdominal pain. The episode caused an outcry among parents and politicians, prompting tests of all artificial colorants. Some of the coal-tar dyes — different colors were created by mixing the hydrocarbons with other chemical compounds — were found to be relatively safe, but nearly every rat and dog given Orange No. 1 showed signs of distress, ranging from weight loss to death. Scientists deemed the dye an acute toxin. Red No. 32 fared even worse; in one experiment, all 48 rats fed Red No. 32 died.

After years of haggling between government and industry, a Supreme Court ruling in 1958 resulted in a final ban for Orange No. 1 and Red No. 32. Two years later, federal legislation led to the prohibition of numerous other dyes and required more rigorous testing of all food colors, eventually leaving us with the seven colors still in use today: Blue No. 1, Blue No. 2, Green No. 3, Yellow No. 5, Yellow No. 6, Red No. 3 and Red No. 40. But fears were renewed in 1973 when a pediatric allergist from San Francisco named Benjamin F. Feingold presented a paper at a medical conference suggesting that the consumption of artificial colors caused hyperactivity in children. Though he had little but anecdotal evidence to support his theory, Feingold wrote two best-selling books that advised parents to remove artificial colors and flavors from the diets of hyperactive children. Despite the popularity of what was called the Feingold Diet, the production of F.D.A.-certified artificial colorants in the United States surged to more than 17 million pounds of powder in 2015 from 1.6 million pounds in 1955. A study released earlier this year found that 43 percent of all food products marketed to children, and 95 percent of fruit-flavored snacks, contain artificial dyes.

A meta-analysis of 23 studies undertaken in the decade after Feingold first put forward his advice found the link between diet and hyperactivity too small to be statistically significant. But then in 2004 and 2007, two landmark scientific articles, one published in The Lancet, revealed that consuming some artificial colors had a small but noteworthy effect on hyperactivity in more than 300 British children. The studies prompted the European Union in 2010 to begin requiring food labels to clearly note the presence of several artificial dyes along with the warning that they “may have an adverse effect on activity and attention in children.” To avoid having to include that alarming label, many food manufacturers began phasing out synthetic colors in the European market. A year later, an F.D.A. advisory panel voted that no such label was necessary in the United States. (The panel also noted that more research was needed.)

Label or no label, American consumers began to lose their appetite for synthetic dyes, too. A survey of some 26,000 American adults over the last three years shows that a full half of them say they want to avoid artificial colors and preservatives. A recent Nielsen poll ranked the absence of artificial food dyes as the third-most-important factor in food-purchasing decisions among consumers worldwide. Parents have created YouTube testimonials and petitions on change.org claiming that their children have become more focused or their nightmares have gone away after cutting artificial dyes from their diet. Videos and blogs show toddlers turning into “monsters” minutes after eating synthetically colored candies and cupcakes. Some people appeal to companies directly, like the mother of a 9-year-old named Trenton, who said her son abruptly stopped being disruptive at school and hockey practice after he quit eating artificial colors. Her petition to Mars to make M&Ms — one of the boy’s favorite candies — with natural colors received nearly 217,000 signatures.

There are things we still don’t know about how artificial colors interact with the human body. Research shows that Blue No. 1 is the only dye that crosses the blood-brain barrier, which exists to protect the brain from toxins and pathogens. It enters the fluid inside the skull, but scientists know almost nothing about what it does once it’s there. Rather than continue to defend themselves against these growing concerns, big food companies last year began making public commitments to give up synthetic dyes. Fulfilling those promises has set off a quest for novel colors that calls to mind the preindustrial days when explorers and traders traveled the world collecting indigo from South Asia or a dark red powder derived from cochineal insects used by the Aztecs.

The blue-extraction facility looks like just another dun-colored building rising out of Southern California’s Imperial Valley near the Salton Sea. The buildings and sand are the same hue as the maximum-security prison next door, the abundant crickets and the tumbleweeds. This is not somewhere you’d go looking for blue, or any color other than beige. But inside the factory, stainless-steel tanks and industrial-size kilns extract a blue powder from a thick sludge of algae sucked out of 100 acres of man-made ponds nearby. The fine powder coats the white uniforms of workers, collecting in the sweaty creases of their necks and noses, leaving smudges across garbage cans, walls and hand-washing stations like the impressionistic cave paintings of some blue-loving tribe.

This blue-extraction operation, the first in the United States, was opened a year ago by a Japanese chemical company called DIC, which also runs a similar extraction plant in southern China. DIC now produces 90 percent of the world’s supply of spirulina-based blue pigment in these two facilities, and it projects that the market will increase as much as 10-fold over the next two years as the food industry scrambles to replace Blue No. 1. One Mars executive told me that to convert only its blue M&Ms to spirulina blue, the company would, in his estimation, need twice the current global supply. And Mars has committed to converting all the food it makes for humans to natural colors. (Its pet food will still contain artificial colors.)

“Blue is going to just explode,” Amha Belay, the affable, crinkly-eyed chief technology officer at the extraction facility, told me in a lilting Ethiopian accent. We were standing atop the four-story-high hot-air dryer, which turns the wet muck into green powder. About 10 percent of that powder is made up of molecules called phycocyanins, which, when wrested from the green, make the highly prized blue dust. Belay looked proud up there, pointing out across the desert, where the company is planning to nearly double the pond acreage over the next couple of years.

By 9 a.m., the temperature around the blue extractor was already near 100 degrees, and the air was thick with monsoon moisture pushing up from Mexico. “Spirulina like it hot,” Belay said. Microalgae are an especially promising source of natural pigments, not just blues but also oranges, reds, greens and yellows. Scientists estimate that there may be as many as a million different species of microalgae, and Belay is a natural evangelist for the tiny blobs. He grew up in Addis Ababa, not far from alkaline lakes that teemed with naturally growing spirulina and flocks of flamingos, whose bright pink feathers are colored by pigments called carotenoids found in the algae, which is consumed by brine shrimp, which are eaten by the birds. Without carotenoids, flamingos would be gray (and deciduous trees would not erupt in autumnal glory).

Belay and I peeked through a window at the brand-new research-and-development lab next to the extractor. The company, worried that I might give away secrets about its methods and technology, wouldn’t let me inside, but behind the glass I could see Japanese researchers trying to extract other colors from the pond slime. The search feels almost feverish; last year the global market in natural colors was worth an estimated $970 million, up 60 percent since 2011. Natural colors now represent more than half the food-colors market in dollar terms. From here, the blue powder will go to one of the large dye companies (known as the color houses), whose scientists will further tinker with it before selling it to food companies like Mars.

“Blue is just the beginning,” said Belay, who thinks about color not as a static thing but as a dynamic universe of visible light. Looking at a mound of algal glop, he knows that it appears green because in the process of converting the sun’s energy, the algae’s chlorophyll molecules absorb blue and red waves and reflect green back to our eyes. Vision is a subtractive process: The human eye sees only what’s left behind, unabsorbed. Strip away the chlorophyll, and underneath there are other pigment molecules like carotenoids, which can be used to make yellows, reds, oranges and browns. In a handful of soggy spirulina, Belay can see the potential for a sort of Crayola wonderland.

‘Blue, he can’t just be any blue.” Hank Izzo, a vice president of research and development, kept using male pronouns to refer to the color blue while I was at Mars in Hackettstown. This confused me at first. It seemed off, maybe even sexist. Why was blue a he? Then, when we entered a conference room, he pointed to the wall and said: “Wherever he is, he needs to be that blue.” And there they were, painted on the wall behind me, those bulbous, anthropomorphic M&M characters that show up in TV commercials. The green and brown M&Ms are female, with long eyelashes and white high heels. The rest of the colors are male. Blue’s official webpage reveals that his turn-ons are “moonlit nights, jazz, the ladies.”

Everyone I talked to at Mars insisted that they needed to find natural colors that exactly replicate the current artificial ones. The changing of an extremely popular food’s color is viewed warily for legitimate reasons. Humans have learned over millenniums to see in colors signposts indicating safety and danger, so we can avoid having to stick everything in our mouths to find out whether it is poisonous or not.

There are two dominant theories about why human vision evolved as it did. Either our perception of color helped us locate food, training us to differentiate the reds of ripened fruit from green foliage, or the way we see emerged from our need to detect changes in one another’s skin tone that might indicate anger or sexual arousal. However it developed, the human perception of color is, like emotion, experiential. As soon as we open our eyes each morning, we’re surrounded by shimmering light that must be converted into something knowable and navigable. Humans can ordinarily distinguish more than two million different colors. Instead of continually reconstructing images of everything we see, our brains take shortcuts by creating color memories as filters. A ripe banana is assigned a particular yellow based on previous experience with bananas. Researchers call this the “memory color effect,” and not all cultures see and know colors in the same way. A global food conglomerate like Mars, which sells products in 150 countries, wants its goods to be uniformly recognizable anywhere in the world. Aided by marketing and chemistry, brands fight against the different experiences of individual retinas. Companies want their colors to become, in essence, memory colors for the entire species.

People also don’t like the taste of change (or think they don’t). Market researchers point out that if a company calls attention to a tweak in a product (a shift in color, for example, or new “natural” or “healthy” labeling), consumers will claim to taste a difference — even when there is none — and they won’t like it. To compare the natural pigments with their artificial counterparts, Mars uses a colorimeter that measures the exact absorbance of specific wavelengths of light. It knows, for example, that the M&M colored with Blue No. 1 is more cyan than the one colored with spirulina. The company is continually running tasting panels with consumers, and they indicate Americans are especially sensitive to even slight alterations in color. If a naturally colored M&M tastes the same but has a lighter tinge, Americans will say it does not taste “as fun,” while Europeans are more likely to accept such slight color changes or miss them altogether. The enormous amount of money and effort researchers at food companies are putting into the development of highly saturated natural colors is partly an effort to maintain the status quo, the legacy of products through time. But they also know that, biologically speaking, deep, contrasting colors are more attractive to people than mere nostalgia for a specific candy.

Just adding a red coloring can make food taste 10 percent sweeter. In one well-known 1980 study, researchers gave people differently colored beverages. Some drinks appropriately matched colors and flavors (cherry with red, say), while others scrambled them. More than a quarter of the taste testers reported that the cherry-flavored drink had a lemon-lime taste when it was colored green, but no one mentioned lemon-lime when the same cherry drink was red. Their brains determined flavors based on color before the liquid touched their tongues.

Colors can also influence how much people eat. The greater the variety of colors consumed, the longer it takes someone to feel full. Scientists call this phenomenon “sensory-specific satiety.” “If you look at something that has five or six different colors in it, you go, Wow, that’s going to be fun to eat,” says Brian Wansink, director of the Food and Brand Lab at Cornell University. “Even if someone says to you, ‘All those M&Ms taste exactly the same.’ It doesn’t matter. Your mind sees that variety as more enjoyable and tempting than a plain bowl of blue M&Ms, and so you eat more.”

Why anyone wants to eat blue foods in the first place has long confused food scientists. In the natural world, the color tends to flag the presence of things to avoid, like mold, spoiled meat or poisonous berries. People asked to name flavors associated with specific colors easily rattle off answers. Yellow? Bananas, lemons. Red? Cherries, strawberries, apples, ripeness. But blue stumps people, after they mention blueberries. In one study, British participants associated blue with raspberry; in Taiwan, subjects linked blue to mint. But these flavor associations have nothing to do with what’s growing in the soil or ripening on the vine and are instead flavor-color connections created by food companies. Blue was, in some ways, the final frontier in food coloring. Survey respondents around the world overwhelmingly say their favorite color is blue. Yet in the 1960s and ’70s, marketers and food anthropologists argued that consumers would reject the inherently unappetizing color. In a famous study from the era, a researcher fed subjects steak under color-masking lights. Halfway through the meal, he switched on the regular lights to reveal that the steaks were dyed blue, which induced nausea and illness in the participants who had, until then, been relishing the meat.

The predictions that blue food would fail were, of course, wrong. Gatorade introduced the first of several blue drinks in 1995. Blue M&Ms came out the same year, after consumers chose the new color over pink and purple in a contest. By the early 2000s, Heinz had introduced a teal-colored ketchup, Kraft a blue macaroni and cheese and Kellogg’s a cereal that turned milk baby blue. The most gimmicky blue products were eventually discontinued, but the color became a mainstay, especially in the “fun foods” category dominated by candy, sugary drinks and cereals.

Look at a bowl of naturally colored Trix cereal set beside its artificially colored predecessor. The effect is akin to putting a watercolor of a desert landscape next to an Andy Warhol print: Nature’s colors are more muted, gentle. For many snack and candy makers, that wimpy palette will not suffice. Until more vibrant colors can be extracted from nonsynthetic sources, some food marketers may have to rely on manipulating visual responses in other ways. “Consumers mostly want things to stay the same as they always have, to taste the same as they always have, to look the same as they always have,” says Charles Spence, a professor of experimental psychology at Oxford University whose research has shown that so-called extrinsic colors surrounding a food item — the color of the plate, say, or flatware — influence how people see and experience what they’re eating. In one of Spence’s studies, participants rated a pink strawberry mousse as 10 percent sweeter and 15 percent more flavorful when eaten from a white plate compared with a black plate. He’s now consulting with food manufacturers that want to alter their packaging so consumers will be less likely to notice the subtler colors produced by natural dyes.

The Mars color scientists circled me, looking worried, even protective. The first item on our menu was an M&M dyed blue with spirulina. After that, they gave me a vermilion one colored with radish, a bright yellow one (turmeric root), a deeper red one (beet), jelly beans tinted with purple carrots and spirulina-blue Skittles and Starbursts. “I think you’re the first person in the world who doesn’t work for Mars to taste those,” someone told me.

“Do you need a spit cup?”

“Someone get her some water, quick.”

Despite the furrowed brows of the scientists, the spirulina-blue M&M tasted good. The hard sugar coating clicked pleasantly against my teeth just before releasing that familiar wash of milk chocolate, the same as any M&M. When I nodded approvingly, the scientists seemed to be relieved. It’s true, the blue is not the same — “It’s a different blue, but that doesn’t necessarily make it a bad blue,” Robbins, the color-chemistry manager, said — but it is vibrant, chipper even, and does not come across as a shoddy knockoff. My approval, as a proxy for sweet-toothed consumers, seemed to make these scientists a little giddy.

But that changed when we moved on to the spirulina Skittle. I could feel the nervousness of the white-smocked group rise as I was handed a small, clear, plastic cup — the kind hospitals sometimes use to administer medications — containing a single round blue candy. I put it on my tongue, and at first all I noticed was the tart hit of sugar and acid inducing that expected rush of saliva. I’ve never chewed under such scrutiny. I quickly swallowed and smiled reassuringly. “Just wait,” Robbins said, and then there it was: a distinct, boggy, shallow-pond-in-late-summer aftertaste.

I would have spit, but the scientists seemed so vulnerable already. I took a gulp of water. Their disappointment was understandable: They’ve spent years trying to control these rowdy pigments when what they need and want is something stable and predictable. I felt for them. But I could not help rooting for the spirulina-blue phycocyanin molecule, doggedly carrying with it the turbid water where it grew, the scalding sun in a cloudless azure sky, the white birds wheeling above, hovering for a moment to catch insects on the water’s surface. How brazen this little bit of blue, untamed by the industrial dryers and stainless-steel separation tanks at the pigment-extraction facility; unwilling to be broken by the labs at the big biosciences companies that take that blue powder, further refine it and sell it to food companies as dye. It’s obstinate, even here, so many chemical interventions later, at Mars, where it manifests a whisper of its origin story in a Skittle. Just a faint, lingering flavor, as if to say, “I’m blue because the world, in all its unruly variety, made me this color.”

Malia Wollan is a frequent contributor to The New York Times and the Tip columnist for the magazine. She lives in Oakland, Calif.