pythonggplot2plotnine

How to move x-axis on top of the plot in plotnine?


I am using plotnine with a date x-axis plot and want to put x-axis date values on top of the chart but couldn't find a way to do it.

I have seen in ggplot it can be done using scale_x_discrete(position = "top") but with scale_x_datetime() I couldn't find any position parameter in plotnine.

Below is the sample code:

import pandas as pd
from plotnine import *

# Create a sample dataset
data = pd.DataFrame({
    'date': pd.date_range('2022-01-01', '2022-12-31',freq="M"),
    'value': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
})

# Create the line chart
(ggplot(data, aes(x='date', y='value')) + 
    geom_line() + 
    labs(title='Line Chart with Dates on X-Axis', x='Date', y='Value') + 
    theme_classic()
)

Would really appreciate any help !!

Update (facet plot) after the answer:

# sample dataset
new_data = {
    'date': pd.date_range('2022-01-01', periods=8, freq="ME"),
    'parent_category': ['Electronics', 'Electronics', 'Fashion', 'Fashion', 'Home Goods', 'Electronics', 'Fashion','Electronics'],
    'child_category': ['Smartphones', 'Laptops', 'Shirts', 'Pants', 'Kitchenware','Laptops', 'Shirts', 'Smartphones']
}

# Create DataFrame
new_data = pd.DataFrame(new_data)

new_data

plot with answer tips

(ggplot(new_data, aes(x="date", y="child_category", group="child_category")) +
    geom_line(size=1, color="pink") +
    geom_point(size=3, color="grey") +
    facet_wrap("parent_category", ncol=1, scales="free_y") +
    theme_538() +
    theme(axis_text_x=element_text(angle=45, hjust=1),
          panel_grid_major=element_blank(),
          figure_size=(8, 6),
          axis_line_x=element_line(position=('axes',1)))
)

enter image description here

In facet plot it doesn't go to top of the chart.


Solution

  • Try this:

    # Create the line chart
    (ggplot(data, aes(x='date', y='value')) + 
        geom_line() + 
        labs(title='Line Chart with Dates on X-Axis', x='Date', y='Value') + 
        theme_classic() + 
        theme(axis_line_x=element_line(position=('axes', 1)))
    )
    

    Here's the source code explanation/implementation for position=(axes, 1) for more clarity.

    Update:

    For the sake of completeness here's more detail on the facet plot for the updated question (all credit goes to @ViSa for figuring this out in the comments):

    According to the source code of plotnine for facet_wrap:

    scales : Whether x or y scales should be allowed (free) to vary according to the data on each of the panel.

    And the allowed values are: "fixed", "free", "free_x", "free_y" with the default value being "fixed".

    So, setting scales to free_x or free should resolve the problem shown in the image shared in the question.

    facet_wrap("parent_category", ncol=1, scales="free_x")
    

    Here's the updated image with this change:

    facet plot