Tom Kurushingal
Tom Kurushingal

Reputation: 6496

How to rotate labels to follow contours in Python?

I have data (link) of the form given below:

Y   X 0 X 10    X 20
15  4.83    4.91    4.99
20  4.58    4.65    4.73
25  4.43    4.49    4.56

I am trying to plot contours of the X label values, in these cases 0, 10, 20 (as z in code) with x-axis as X values and y-axis as Y values. Plots are created using the code:

import numpy as np
import re
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import matplotlib.cm as cm

with open('contour.dat', "r") as data:
    while True:
        line = data.readline()
        if not line.startswith('#'):
            break
    data_header = [i for i in line.strip().split('\t') if i]
_data_ = np.genfromtxt('contour.dat', skiprows = 2, delimiter = '\t')
x = _data_[:, 0]
y = _data_[:, 1:]


y_n = []
for i in range(len(data_header)):
    if data_header[i][0] == 'X':
        y_n = np.int_(np.append(y_n, i))
y_index = [data_header[i] for i in y_n]
z = []
for i in range(0, len(data_header)):
    z = np.append(z, re.findall(r"[-+]?\d*\.\d+|\d+", data_header[i]))
z = z.reshape(len(z), 1)
xm = np.tile(x, 21)
xm = np.reshape(xm,(21, 10)).T
zm = np.tile(z, 10).T

with PdfPages('./on_tau.pdf') as p_tau:
    _p_vs_tau_ = plt.figure(figsize=(5, 5))
    _p_vs_tau_.clf()
    p_vs_tau = plt.subplot(111)
    # x, y = np.meshgrid(x, y)
    surf = plt.contourf(y, xm, zm, 22, rstride=1, cstride=1, cmap=cm.gist_heat,
                           linewidth=0, antialiased=False, alpha = 1.0)
    surf1 = plt.contour(y, xm, zm, 22, colors = '#000000',
                           linewidths=0.5, antialiased=False, alpha = 1.0)
    plt.clabel(surf1, inline=1, fontsize=6)
    plt.xlim([5, 10])
    p_tau.savefig(bbox_inches='tight')
    plt.close()

I am trying to solve the following issues:

1. At present all the contour labels are vertical. How can I rotate the labels to follow the contours?

2. How to change the position of the labels so that they do not overlap (as shown in figure)?

enter image description here

Additional question

3. How to ensure that labels are always shown on plots even if axis limits are changed?

Upvotes: 1

Views: 1538

Answers (1)

nicoguaro
nicoguaro

Reputation: 3871

I ran the code below in matplotlib 1.4.3 and obtained rotated contour labels as you wanted, so, I don't know why you have that problem. For your second question, what about using less contour levels?

import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

x, y = np.pi*np.mgrid[-1:1:101j, -1:1:101j]
z = np.sin(x)*np.sin(y)

with PdfPages('./contour_plot.pdf') as p_tau:
    _p_vs_tau_ = plt.figure(figsize=(5, 5))
    _p_vs_tau_.clf()
    p_vs_tau = plt.subplot(111)
    surf = plt.contourf(y, x, z, 21, rstride=1, cstride=1, cmap="RdYlBu",
                           linewidth=0, antialiased=False, alpha = 1.0)
    surf1 = plt.contour(y, x, z, 21, colors='k', linestyles="solid",
                           linewidths=0.5, antialiased=False, alpha = 1.0)
    plt.clabel(surf1, inline=1, fontsize=6)
    plt.savefig("contour_plot.png", dpi=600)
    p_tau.savefig(bbox_inches='tight')    
    plt.close()

enter image description here

Upvotes: 1

Related Questions