Zichzheng
Zichzheng

Reputation: 1290

Matplotlib Draw a Constant y Axis

I want to use matpoltlib to make a plot that with a constant y axis(always from 0 to 14 and the gap is 1), since I want to make labels for them and my dot values will be(x, y) where y is from 0 to 14 gap 1, and a changing x axis. I already tried to play with y ticks. And here is my code for that:

    fig, ax = plt.subplots()
    fig.canvas.draw()
    plt.yticks(np.arange(0, 14, 1))
    labels = [item.get_text() for item in ax.get_yticklabels()]
    labels[1] = 'Not Detected'
    labels[2] = 'A/G'
    labels[3] = 'G/G'
    labels[4] = 'C/T'
    labels[5] = 'C/C'
    labels[6] = 'A/A'
    labels[7] = '-1'
    labels[8] = 'ε3/ε3'
    labels[9] = 'A/C'
    labels[10] = 'T/T'
    labels[11] = 'C/G'
    labels[12] = 'ε2/ε3'
    labels[13] = 'G/T'

    ax.set_yticklabels(labels)

what I'm thinking about is to use some values or lines with white color so those y axis will appear. But I'm looking for a more efficient way of doing it. And here is the diagram I generated with the current code. It only shows C/C right now and I want all labels to appear in the diagram. enter image description here

I tried draw white points with:

    x1 = np.arange(n)
    y1 = np.arange(1,15,1)
    plt.scatter(x1,y1,color = 'white')

Which did give me what I want: But I was wondering whether there is a lib setting that can do this. enter image description here

Upvotes: 0

Views: 819

Answers (1)

Coup
Coup

Reputation: 750

I would recommend just using a fixed locator and fixed formatter for your y axis. The function, ax.set_yticklabels() is simply a convenience wrapper for these tick methods.

I would also recommend having your y_labels in a list or using a loop structure as this is a more generalizable and modifiable implementation.

If I'm understanding the goals of your plot correctly, something like this may work well for you.

enter image description here

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

#make some data
x = np.arange(25)
y = np.random.randint(1, 14, size=25)

#convert y labels to a list
y_labels = [
    'Not Detected','A/G','G/G','C/T','C/C','A/A',
    '-1','ε3/ε3', 'A/C','T/T','C/G','ε2/ε3','G/T'
    ]

#define figure/ax and set figsize
fig, ax = plt.subplots(figsize=(12,8))
#plot data, s is marker size, it's points squared 
ax.scatter(x, y, marker='x', s=10**2, color='#5d2287', linewidth=2)

#set major locator and formatter to fixed, add grid, hide top/right spines
locator   = ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(np.arange(1, 14)))
formatter = ax.yaxis.set_major_formatter(mpl.ticker.FixedFormatter(y_labels))
grid      = ax.grid(axis='y', dashes=(8,3), alpha=0.3, color='gray')
spines    = [ax.spines[x].set_visible(False) for x in ['top','right']]
params    = ax.tick_params(labelsize=12) #increase label font size

Upvotes: 1

Related Questions