Customize Axis Labels

Modify tick label text

Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than 1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be...

Normally, you'd do something along these lines:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# We need to draw the canvas, otherwise the labels won't be positioned and
# won't have values yet.
fig.canvas.draw()

labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Testing'

ax.set_xticklabels(labels)

plt.show()

Sample Image

To understand the reason why you need to jump through so many hoops, you need to understand a bit more about how matplotlib is structured.

Matplotlib deliberately avoids doing "static" positioning of ticks, etc, unless it's explicitly told to. The assumption is that you'll want to interact with the plot, and so the bounds of the plot, ticks, ticklabels, etc will be dynamically changing.

Therefore, you can't just set the text of a given tick label. By default, it's re-set by the axis's Locator and Formatter every time the plot is drawn.

However, if the Locators and Formatters are set to be static (FixedLocator and FixedFormatter, respectively), then the tick labels stay the same.

This is what set_*ticklabels or ax.*axis.set_ticklabels does.

Hopefully that makes it slighly more clear as to why changing an individual tick label is a bit convoluted.

Often, what you actually want to do is just annotate a certain position. In that case, look into annotate, instead.

How do I customize y-axis labels on a Chart.js line chart?

In the ticks object you can pass a callback that will be given the label it is about to show. From here you just return a string you wish to display in place of the label.

chart.js-V2.X fiddle exampe
chart.js-V3.X fiddle exampe

ticks: {
min: 0,
max: 5,
stepSize: 1,
suggestedMin: 0.5,
suggestedMax: 5.5,
callback: function(label, index, labels) {
switch (label) {
case 0:
return 'ZERO';
case 1:
return 'ONE';
case 2:
return 'TWO';
case 3:
return 'THREE';
case 4:
return 'FOUR';
case 5:
return 'FIVE';
}
}
}

How to make y axis labels horizontal but keep y-axis title parallel?

An alternative way to set the y axis labels parallel is as follows.
(1) Set both of the ylab and rylab from twoord.plot to empty.
(2) Use mtext and set the parameters accordingly.

Here is the code to do that. Because you don't provide the distribution data, I use iris data just to make it possible to generate the plot.

# Emptying both of ylab and rylab

twoord.plot(data = iris,lx="Sepal.Length",ly="Petal.Width", ry="Sepal.Width",
main="B1 Surface Grain Size Distribution",
xlim=NULL,lylim=c(0,160),rylim=NULL,lwd=1.5,
lcol=1,rcol=2,xlab="Grain Size (mm)",lytickpos=yFrequency,
ylab="",ylab.at=NA,
rytickpos=NA,rylab="",rylab.at=NA,
lpch=1,rpch=2,
type="b",xtickpos=NULL,xticklab=GS_class_labels,
halfwidth=0.4,axislab.cex=1.1,
do.first=NULL,xaxt="n",yaxt="n", #yticklab=yFrequency,
cex.lab=1)

# Assign the previous labels of ylab and rylab to the *text* parameter of *mtext*.
# side = 2 means the left side. side = 4 means the right side.
# las = 0 is the parallel style of the text.
# line shows the distance of the text from the y axis.

mtext(text = "Frequency", side = 2, las = 0, line = 2.5)
mtext(text = "Percent Finer Than (%)", side = 4, las = 0, line = 0.5)

The resulted plot:

Sample Image

How to change the x-axis and y-axis labels in plotly?

  • simple case of setting axis title
update_layout(
xaxis_title="Date", yaxis_title="7 day avg"
)

full code as MWE

import pandas as pd
import io, requests

df = pd.read_csv(
io.StringIO(
requests.get(
"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv"
).text
)
)
df["Date"] = pd.to_datetime(df["date"])
df["Country"] = df["location"]
df["7day_rolling_avg"] = df["daily_people_vaccinated_per_hundred"]

Date = df[df.Country == "India"].Date
New_cases = df[df.Country == "India"]["7day_rolling_avg"]

px.line(df, x=Date, y=New_cases, title="India Daily New Covid Cases").update_layout(
xaxis_title="Date", yaxis_title="7 day avg"
)

R Sample Image 18

customize x axis label placement in ggplot + coord_polar

You can simply adjust the breaks and labels on the x axis. I think it also improves the appearance to have curved labels and perhaps some year dividers:

library(geomtextpath)

ggplot(d, aes(year, cover, color = species)) +
geom_rect(data = data.frame(y = c(2017, 2017 + 2/3, 2018 + 1/3)),
aes(ymax = Inf, ymin = -Inf, xmin = y, xmax = y + 2/3),
inherit.aes = FALSE, alpha = 0.05, color = "gray75") +
geom_line(size = 2) +
coord_curvedpolar() +
theme_classic() +
scale_x_continuous(breaks = c(2017.33, 2018, 2018.67), labels = 2017:2019) +
theme(text = element_text(size = 18),
legend.text = element_text(face = "italic"),
legend.title=element_blank(),
legend.position="right",
axis.line.x.bottom = element_blank())

Sample Image

Changing the axis labels in a group of stacked bar charts

You may try this way. Please let me know if I miss something or I'm wrong with your purpose.

df2 %>% 
group_by(cat1, cat2) %>%
mutate(n = sum(as.integer(value))) %>%
rowwise %>%
mutate(cat1 = paste0(c(cat1, n), collapse = "\n")) %>%
ggplot(aes(x = cat1, y = value, fill = cat3, label = as.integer(value))) +
geom_bar(stat = 'identity', position = 'stack') +
geom_text(position = position_stack(vjust = 0.5), size = 3, color = "#555555") +
geom_errorbar(aes(ymin = agg, ymax = agg)) +
facet_wrap(~ cat2, scales = "free_x", ncol = 6)

Sample Image



Related Topics



Leave a reply



Submit