David M Vermillion
David M Vermillion

Reputation: 163

How do I move the axis labels in plotnine?

I'm trying to move the x and y axis labels to be near each other at the bottom left of the chart.

This is easy enough in R's ggplot2 with:

theme(
axis.title.y = element_text(angle = 0, vjust = 0, hjust = 0.5, size = 15,
color = "grey55"),
axis.title.x = element_text(hjust = 0, size = 15, color = "grey55"))

However, it results in unexpected behavior in plotnine where the labels only move a few millimeters with the standard arguments. This code sample uses the plotnine terms, but results in the same bizarre behavior.

Misbehaving Labels

p1 = [39.5,
 117.2,
 129.4,
 0.7,
 87.2,
 164.5,
 224.0,
 110.7,
 121.0,
 191.1,
 4.1,
 104.6,
 125.7,
 136.2,
 202.5,
 76.3,
 216.8,
 19.6,
 75.3,
 120.2,
 287.6,
 237.4,
 97.2,
 248.8,
 67.8,
 151.5,
 116.0,
 213.5,
 188.4,
 265.2]
p1_1 = pd.DataFrame(p1, columns = ['Test'])

# Histogram

(
 p9.ggplot(p1_1, p9.aes(x = 'Test'))
 + p9.geom_histogram(bins = N/6, fill = "#f9d9d6", color = "#E34234")
 + p9.theme_classic()
 + p9.themes.theme(
        axis_title_y = p9.themes.element_text(va = 'bottom', angle = 0, ha = 'center', size = 15, color = "#8c8c8c"),
      axis_title_x = p9.themes.element_text(hjust = 0, size = 15, color = "#8c8c8c"),
      axis_text = p9.themes.element_text(size = 12, color = "#999999"),
      axis_line = p9.themes.element_line(color = "#999999"),
      axis_ticks = p9.themes.element_line(color = "#999999"),
      plot_title = p9.themes.element_text(hjust = 0.5, size = 40, color = "#666666"), 
      panel_grid = p9.themes.element_blank(),
      )
).draw();

Upvotes: 2

Views: 1980

Answers (1)

stefan
stefan

Reputation: 125338

Following this comment on related GitHub issue with respect to plot_title you could shift the positions by setting the x and the y positions of the axis titles. For your desired result I think y=.1 and x=.125 work fine:

(p9.ggplot(p1_1, p9.aes(x = 'Test'))
 + p9.geom_histogram(bins = 10, fill = "#f9d9d6", color = "#E34234")
 + p9.theme_classic()
 + p9.themes.theme(
      axis_title_y = p9.themes.element_text(angle = 0, va = 'bottom', ha = 'right', 
                                            size = 15, color = "#8c8c8c", y = .1),
      axis_title_x = p9.themes.element_text(ha = 'left', va = 'center', size = 15, 
                                            color = "#8c8c8c", x = 0.125),
      axis_text = p9.themes.element_text(size = 12, color = "#999999"),
      axis_line = p9.themes.element_line(color = "#999999"),
      axis_ticks = p9.themes.element_line(color = "#999999"),
      plot_title = p9.themes.element_text(hjust = 0.5, size = 40, color = "#666666"), 
      panel_grid = p9.themes.element_blank(),
      )
)

enter image description here

Upvotes: 4

Related Questions