Square root scale using matplotlib/python

matplotlib log2 scale
pylab plot
matplotlib plot size
how to change y axis scale in python
python plot defined function
matplotlib log scale
how to change scale in matplotlib
square root python

I want to make a plot with square root scale using Python:

However, I have no idea how to make it. Matplotlib allows to make log scale but in this case I need something like power function scale.

You can make your own ScaleBase class to do this. I have modified the example from here (which made a square-scale, not a square-root-scale) for your purposes. Also, see the documentation here.

Note that to do this properly, you should probably also create your own custom tick locator; I haven't done that here though; I just manually set the major and minor ticks using ax.set_yticks().

import matplotlib.scale as mscale
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib.ticker as ticker
import numpy as np

class SquareRootScale(mscale.ScaleBase):
    """
    ScaleBase class for generating square root scale.
    """

    name = 'squareroot'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)

    def set_default_locators_and_formatters(self, axis):
        axis.set_major_locator(ticker.AutoLocator())
        axis.set_major_formatter(ticker.ScalarFormatter())
        axis.set_minor_locator(ticker.NullLocator())
        axis.set_minor_formatter(ticker.NullFormatter())

    def limit_range_for_scale(self, vmin, vmax, minpos):
        return  max(0., vmin), vmax

    class SquareRootTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def transform_non_affine(self, a): 
            return np.array(a)**0.5

        def inverted(self):
            return SquareRootScale.InvertedSquareRootTransform()

    class InvertedSquareRootTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def transform(self, a):
            return np.array(a)**2

        def inverted(self):
            return SquareRootScale.SquareRootTransform()

    def get_transform(self):
        return self.SquareRootTransform()

mscale.register_scale(SquareRootScale)

fig, ax = plt.subplots(1)

ax.plot(np.arange(0, 9)**2, label='$y=x^2$')
ax.legend()

ax.set_yscale('squareroot')
ax.set_yticks(np.arange(0,9,2)**2)
ax.set_yticks(np.arange(0,8.5,0.5)**2, minor=True)

plt.show()

matplotlib.pyplot.yscale, scale.register_scale . These scales can then also be used here. Examples using matplotlib.pyplot.yscale  To calculate Square roots in Python, you will need to import the math module. This module consists of built-in methods namely sqrt() and pow() using which you can calculate the square roots. You can import it by simply using the import keyword as follows: Once this module is imported, you can make use of any function present within it.

I like lolopop's comment and tom's answer, a more quick and dirty solution would be using set_yticks and set_yticklabels as in the following:

x = np.arange(2, 15, 2)
y = x * x

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(x,y)

ax2.plot(x, np.sqrt(y))
ax2.set_yticks([2,4,6,8,10,12,14])
ax2.set_yticklabels(['4','16','36','64','100','144','196'])

matplotlib.pyplot.yscale, scale.register_scale . These scales can then also be used here. Examples using matplotlib.pyplot.yscale  Using loop; Python Square root of a Number using pow() Calculating Square Root in Python Using sqrt() Function. Python math module deals with mathematical functions and calculations. Function sqrt() in the math module is used to calculate the square root of a given number. Syntax. Following is the syntax for Python sqrt() function.

Matplotlib now offers a powlaw norm. Thus setting power to 0.5 should do the trick!

C.f. Matplotlib Powerlaw norm

And their example:

"""
Demonstration of using norm to map colormaps onto data in non-linear ways.
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.mlab import bivariate_normal

N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]

'''
PowerNorm: Here a power-law trend in X partially obscures a rectified
sine wave in Y. We can remove gamma to 0.5 should do the trick using  PowerNorm.
'''
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**(2.)

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.),
                       cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
fig.show()

Python Data Visualization with Matplotlib, We will use Python's Matplotlib library which is the de facto standard for data the graph of the square root of the same data within the other graph for cube axis. A brief introduction to square roots; The ins and outs of the Python square root function, sqrt() A practical application of sqrt() using a real-world example; Knowing how to use sqrt() is only half the battle. Understanding when to use it is the other. Now, you know both, so go and apply your newfound mastery of the Python square root function!

[PDF] Basic Plotting with Python and Matplotlib, For those of you familiar with MATLAB, the basic Matplotlib syntax is very similar. 1 Line plots. The basic syntax for creating line plots is plt.plot(x,y), where x and y are arrays of the same length that specify the (x, y) Z = np.sqrt(X**2 + Y**2) Notice that the aspect ratio is still equal after changing the axis limits. Also, the  You must have been able to draw line chart using matplotlib. In the similar way area chart is just a line chart . Only difference is that the area between the x -axis and the line is filled with color. You will use the function fillbetween(x,y) function of matplotlib library to use this. Below is the code for the simple area chart plotting example.

4. Visualization with Matplotlib, Matplotlib is a multiplatform data visualization library built on NumPy arrays, … In [ 13 ]: plt . plot ( x , np . sin ( x )) plt . axis ( 'equal' ); xfit [:, np . newaxis ], eval_MSE = True ) dyfit = 2 * np . sqrt ( MSE ) # 2*sigma ~ 95% confidence region​. We will use Python's Matplotlib library which is the de facto standard for data visualization in Python. The article A Brief Introduction to Matplotlib for Data Visualization provides a very high level introduction to the Matplot library and explains how to draw scatter plots, bar plots, histograms etc.

Python Machine Learning Cookbook: Over 100 recipes to progress , In fact, the x and y axis of a bubble chart are numerical scales, so the position in weighed scale, the radius must be chosen in proportion to the square root of the Matplotlib at https://matplotlib.org/ api/_as_gen/matplotlib.pyplot.scatter.​html. How to equalize the scales of x-axis and y-axis in Python matplotlib? command to get a square plot with the same scale and ticks for both axis. root out low

Comments
  • Look inside: matplotlib.org/examples/api/custom_scale_example.html
  • as far as I understand "tick mechanics" it will just force false labales. Plot axes will look like square root scale, but data display won't transform, thus plot will be completely misleading.
  • @michal_2am Agreed. Its bad practice to disassociate the tick labels from the data
  • that's why I called it 'quick and dirty'.