'Making a plot that has an x-axis that has neg. values representing hours prior to the start of the event, then pos. values representing hours after

I'm not sure if my question makes sense, so apologies on that.

Basically, I am plotting some data that is ~100 hours long. On the x-axis, I want to make it so that the range goes from -50 to 50, with -1 to -50 representing the 50 hours prior to the event, 0 being in the middle representing the start of the event, and 1-50 representing the 50 hours following the start of the event. Basically, there are 107 hours worth of data and I want to try to divide the hours between each side of 0.

I initially tried using the plt.xlim() function, but that just shifts all the data to one side of the plot.

I've tried using plt.xticks and then labeling the x ticks with "-50", "-25", "0", "25", and "50", and while that somewhat works, it still does not look great. I'll add an example figure of doing it this way to add better clarification of what I'm trying to do, as well as the original plot:

Original plot:

Original Plot

Goal:

Goal Plot

edit

Here's my code for plotting it:

fig_1 = plt.figure(figsize=(30,20))
file.plot(x='start',y='value')
plt.xlabel('hour')
plt.ylabel('value')
plt.xticks([0,25,50,75,100],["-50","-25","0","25","50"])


Solution 1:[1]

You could obtain a zero mean for the ticks using df.sub(df.mean() or np.mean().

Alternative 1:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# generate data
left = np.linspace(10,60, 54)
right = np.linspace(60,10, 53)

noise_left = np.random.normal(0, 1, 54)
noise_right = np.random.normal(0, 1, 53)
all = np.append(left + noise_left, right + noise_right)
file = pd.DataFrame({'start':np.linspace(1,107,107),'value':all})

# subtract mean
file['start'] = file['start'].sub(file['start'].mean())

fig_1 = plt.figure(figsize=(30,20))
file.plot(x='start',y='value')
plt.xlabel('hour')
plt.ylabel('value')

Output:

Output

Alternative 2:

# subtract the mean from start to obtain zero mean ticks
ticks = file['start'] - np.mean(file['start'])

# set distance between each tick to 10
plt.xticks(file['start'][::10], ticks[::10],rotation=45)

output

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1