How to Manually Set Colors in a Bar Chart

How to manually set colors in a bar chart

you can use scale_fill_manual to control the colours.

So your call to ggplot becomes

ggplot(data=data, aes( x = Time,  y=value, fill=variable))   +  
geom_bar(stat="identity") +
ggtitle("% ") + xlab("Time") +
ylab("Percentage") +theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_fill_manual(values=c("purple","black","red"))

How to set different colors for specific columns in matplotlib bar chart?

You can iterate over the bars and use set_color() to update the color manually.

import matplotlib
import matplotlib.pyplot as plt

ax = unioned.plot(kind="bar", x="club_name", y="overall", xlabel="", figsize=(15,5))

# Highest ratings
for i in range(0, 10):
ax.get_children()[i].set_color("red")

# Lowest ratings
for i in range(10, 20):
ax.get_children()[i].set_color("blue")

legends = [
matplotlib.patches.Patch(color="red", label="Highest ratings"),
matplotlib.patches.Patch(color="blue", label="Lowest ratings"),
]
ax.legend(handles=legends, prop={"size": 20})

plt.show()

Plotly: How to manually assign bar colors to categorical lables in go.bar()

You can pass an array of colors to the marker_color parameter in go.Bar, using a dictionary to map each category to your desired color (similar to the example in the documentation here). For example:

import plotly.graph_objects as go

tensions = {
'Supportive': 39,
'Neutral': 27,
'Resistant': 34
}

color_map = {
'Supportive': 'green',
'Neutral': 'yellow',
'Resistant': 'red'
}

items = tensions.items()
x = [item[0] for item in items]
y = [item[1] for item in items]
colors = [color_map[category] for category in x]

fig = go.Figure()
fig.add_trace(
go.Bar(
x=x,
y=y,
marker_color=colors,
width=0.2,
)
)

fig.update_layout(
template='simple_white',
paper_bgcolor='#F9F9FA',
plot_bgcolor='#F9F9FA',
height=200,
margin=dict(
t=20, b=20, l=60, r=40
),
)

fig.update_yaxes(
tickformat=',.0%',
)

fig.show()

Sample Image

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

Sample Image

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)

Sample Image

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

Sample Image

How to put colors in a matplotlib bar chart?

Maybe it is because your dataframe is multiindex columns. Try:

dfPoputationResident.columns = ['Zona', 'Total_MSP']

Another thing you could do is when you groupby to create dfPoputationResident, you can do:

dfPoputationResident = df.groupby('Zona')['Total_MSP'].sum()

instead of

dfPoputationResident = df.groupby('Zona')[['Total_MSP']].sum()

I mean, this works for me:

df = pd.DataFrame({'Zona':list('abcde'),
'Total_MSP':[1,2,3,4,5]})

fig, ax = plt.subplots()

colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
df.plot.bar(x='Zona',y='Total_MSP',color=colors, ax=ax);

ax.legend(ax.patches, df['Zona'], loc=[1.01,0.5])

Output:

Sample Image

How to manually edit the colors in my bar chart without flipping chart orientation

A '+' is missing in one of your ggplot function. (after the labs()).

library(tidyverse)

WE2 <- data.frame(
Age = rep(seq(20, 60, 5), 2),
Gender = rep(c('H', 'F'), each = 9),
n = rnorm(18, 40, 20) %>% ceiling()
) %>%
mutate(n = ifelse(Gender == 'F', -n, n))

WE2 %>% ggplot(aes(x = Age, y = n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == 'H'), stat = "identity") +
geom_bar(data = subset(WE2, Gender == 'F'), stat = "identity") +
scale_y_continuous(breaks = seq(-100,100,10), labels = abs(seq(-100,100,10))) +
scale_fill_manual(values = c("pink", "light blue")) +
labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS") +
coord_flip()

How to use scale_fill_manual to manually define bar plot colors

I would create a dummy variable in your input df2 for the ggplot fill aesthetic. Here, "-999" refers to "OJ" and will be coloured in black.

I've also updated your myPalette to include black in it, and also setNames to it so that only "-999" will have a corresponding "black" value.

library(tidyverse)

df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))

myPalette <- c("#05eb92", "#119da4", "#ffc857")

myPalette_with_black <- setNames(c(myPalette, "black"),
c(as.character(seq_along(myPalette)), "-999"))

df2 <- df2 %>%
group_by(supp) %>%
mutate(dummy = ifelse(supp == "VC", as.character(row_number()), "-999"))

ggplot(data=df2, aes(x=dose, y=len, fill = dummy)) +
geom_bar(stat="identity", position=position_dodge()) +
scale_fill_manual(values = myPalette_with_black) +
theme(legend.position = "none")

Sample Image

Created on 2022-03-12 by the reprex package (v2.0.1)

Set colours for both dimensions of a stacked bar plot

This could be achieved like so:

  1. The issue with the alpha is that you mapped alph on alpha. However, the values for alpha are chosen by ggplot. To set specific alpha values you can e.g. map week on alpha and use scale_alpha_manual to set the alpha values.

  2. To add your colors add the colors as a column to your data, map this column on fill and make use of scale_fill_identity.

library(tidyverse)

teams <- data.frame(
team = factor(LETTERS[1:6], levels = rev(LETTERS[1:6]), ordered = T),
goal = c(200, 160, 200, 250, 220, 180))

weeks <- teams %>%
slice(rep(1:n(), each = 3)) %>%
mutate(week = factor(rep(c(1:3), 6), levels = c(3:1), ordered = T),
alph = 1 - 0.1 * as.numeric(week),
value = c(40, 55, 54, 34, 36, 34, 31, 46, 46, 59, 63, 67, 31, 54, 52, 38, 46, 44),
week_progress = value / goal)

teams <- teams %>%
inner_join(weeks %>% group_by(team) %>% summarise(progress = sum(value)), by = 'team') %>%
mutate(team_progress = progress / goal)
#> `summarise()` ungrouping output (override with `.groups` argument)

ggplot(weeks, aes(x = week_progress, y = team, fill = team)) +
geom_bar(aes(alpha = week), stat = 'identity', position = position_stack(), color = 'black', show.legend = F) +
scale_alpha_manual(values = c(`1` = 0.7, `2` = 0.8, `3` = 0.9)) +
geom_text(aes(group = week, label = scales::percent_format(accuracy = 0.1)(week_progress), x = week_progress),
position = position_stack(vjust = 0.5), color = 'blue')

Sample Image

library(RColorBrewer)

pal <- c(brewer.pal(9, 'YlOrRd')[4:6], brewer.pal(9, 'YlGnBu')[4:6], brewer.pal(9, 'RdPu')[4:6], brewer.pal(9, 'PuBuGn')[4:6], brewer.pal(9, 'Greens')[4:6], brewer.pal(9, 'BrBG')[4:2] )

weeks <- mutate(weeks, cols = pal)

ggplot(weeks, aes(x = week_progress, y = team, fill = cols)) +
geom_bar(stat = 'identity', position = position_stack(), color = 'black', show.legend = F) +
scale_fill_identity() +
geom_text(aes(group = week, label = scales::percent_format(accuracy = 0.1)(week_progress), x = week_progress),
position = position_stack(vjust = 0.5), color = 'blue')

Sample Image

How to change the color bar of chart bars obtained with ggplot2

Just initialize a vector mapping all of the values in v to colors and use it in scale_fill_manual:

require(ggplot2)
d.f<-data.frame(v=c("a","a","b","c","c"),x=c("A","C","T","S","G"),y=10+runif(5))
cols <- c("a"="darkorange2","b"="dodgerblue2", "c"="firebrick2")

pbar <- ggplot(data=d.f, aes(x=x, y=y,fill=v)) +
geom_bar(stat="identity",width=0.8) +
theme(text= element_text(size=16, family = "Times New Roman"),
axis.text.x = element_text(angle = 90,hjust=1, vjust = 0, face="italic", colour="black"),
axis.text.y = element_text(colour="black")) +
coord_cartesian(ylim=c(0.0,12)) +
scale_y_continuous(expand=c(0,0)) +
theme(aspect.ratio = 0.8) +
xlab("Sample")+ylab("Abundance") +
scale_fill_manual(values = cols)

pbar<-pbar+theme(axis.title=element_text(size=18, face="bold"))
pbar<-pbar+theme(axis.text=element_text(size=16))
pbar

Sample Image



Related Topics



Leave a reply



Submit