TornadoEric
TornadoEric

Reputation: 431

Change Precision of Numbers Using Plt.Text

I am plotting data on a map using the plt.text function in Matplotlib. The data for the majority of the plot features values less than 1, and the plots have a precision of 7.

enter image description here

The snippet of code that generates the image is below:

fh = Dataset('/path/to/file/icy.nc', mode='r')
point_list = zip(lat,lon)
dataset_list = []
for i, j in point_list:
    dataset_list.append(fh.variables['ICTHICK'][:][i,j])

for x, y, z in zip(text_lon, text_lat, dataset_list):
    if z in range(-6,6):
        plt.text(x, y, z, color='white', fontsize=12, fontweight='semibold', horizontalalignment='center', transform=crs.LambertConformal())
    #elif:Some other color range here!
    else:
        plt.text(x, y, z, fontsize=12, fontweight='semibold', horizontalalignment='center', transform=crs.LambertConformal()

The goal is to restrict the precision of all plots to two (X.XX). I followed code laid out in a previous post, however upon implementation, there is no change in the precision of the plots. This code alteration is as follows:

plt.text(x, y, r'{0:.2f}'.format(*dataset_list), color='white', fontsize=12, fontweight='semibold', horizontalalignment='center', transform=crs.LambertConformal())

Any advice as to where my current code is going awry?

Upvotes: 2

Views: 5555

Answers (1)

GWW
GWW

Reputation: 44093

The code below works for me:

import pylab as plt
import random

fig, ax = plt.subplots(1, 1, figsize=(5, 5))
for i in range(1, 21):
    #Replace random.random() with z in your case
    ax.text(i, i, "{:.2f}".format(random.random()))
ax.set_xlim(0, 25)
ax.set_ylim(0, 25)

Output:

Output

Upvotes: 6

Related Questions