Home > Software engineering >  Change "Q" quarterly data to custom "kv" in Matplotlib timeline chart on x axis
Change "Q" quarterly data to custom "kv" in Matplotlib timeline chart on x axis

Time:11-04

I have done the following timeline chart in Python. Where the data is in quarterly format by datetimeindex. However, I need to translate the graph into my local language and therefore replace "Q1", "Q2", "Q3", "Q4" with "kv1", "kv2", "kv3", "kv4". Is this possible? So I need the x axsis to be kv3, kv4, kv1 2022, kv2 instead of Q3, Q4, Q1 2022, Q2 and so fourth.

enter image description here

import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import pandas
plt.style.use('seaborn-whitegrid')
matplotlib.rcParams['font.sans-serif'] = "Arial"
matplotlib.rcParams['font.family'] = "Arial"

categories = ['Car','Train','Boat', 'Plane', 'Walk' ]

cat_dict = dict(zip(categories, range(1, len(categories) 1)))

val_dict = dict(zip(range(1, len(categories) 1), categories))

dates = pandas.DatetimeIndex(freq='Q', start='2021-09-30', end='2023-12-31')
values = [random.choice(categories) for _ in range(len(dates))]
df = pandas.DataFrame(data=values, index=dates, columns=['category'])

df['plotval'] = [float('NaN'),1,1,3,1,float('NaN'),5,2,1,float('NaN')]
df['plotval'][0] = np.nan

plt.rcParams["figure.figsize"] = 4,3.5
plt.figure(dpi=1000)
fig, ax = plt.subplots()

df['plotval'].plot(ax=ax, style='^',color='darkblue', label = "Renteheving", markersize=12)

ax.margins(0.2)
ax.spines['top'].set_visible(False)
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: val_dict.get(x)))
plt.yticks( weight = 'bold')

I tried to add

plt.xlabel(["kv1", "kv2", "kv3", "kv4"])

Which gave me

enter image description here

Help is as always highly appreciated.

CodePudding user response:

Try to add this to your code:

# Call draw to populate tick labels
plt.draw()

# Change major labels
new_major_labels = []
for label in ax.get_xticklabels(minor=False):
    s = label.get_text()
    label.set_text(s.replace('Q', 'kv'))
    new_major_labels.append(label)
    
ax.set_xticklabels(new_major_labels, minor=False)

# Change minor labels
new_minor_labels = []
for label in ax.get_xticklabels(minor=True):
    s = label.get_text()
    label.set_text(s.replace('Q', 'kv'))
    new_minor_labels.append(label)
    
ax.set_xticklabels(new_minor_labels, minor=True)

It throws a warning which I don't understand, but I think it does what you want.

CodePudding user response:

I could not test it because I can't reproduce your graph, but this should work:

D = {'Q1':'kv1', 'Q2':'kv2', 'Q3':'kv3', 'Q4':'kv4'}  # define a dictionnary to replace labels

labels = [i.get_text() for i in ax.get_xticklabels()]  # get former labels
labels = [i if i not in D.keys() else D[i] for i in labels]  # replace it if in dictionnary
ax.set_xticklabels(labels)  # apply the new labels
  • Related