简体   繁体   中英

choose scale of x values in matplotlib

I am trying to create a histogram using matplotlib. my X values double, from 2 - 2048. When I graph this on a histogram, there are a bunch of values right next to each other at the start, then it spreads out as the values go up. Since I know I will not have values in between, How can I change the graph to it steps up by a multiple of two? I have tried from matplotlib.pyplot import xticks but that only changes what is displayed.

import matplotlib
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import random
from matplotlib.pyplot import xticks


def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    s = str(100 * y)

    # The percent symbol needs escaping in latex
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'
z = [2, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
x = [z[random.randint(0, 6)] for i in range(100)]
xticks(z)
plt.xscale('log')
# Make a normed histogram. It'll be multiplied by 100 later.
plt.hist(x, bins=50, normed=True)


# Create the formatter using the function to_percent. This multiplies all the
# default labels by 100, making them all percentages
formatter = FuncFormatter(to_percent)

# Set the formatter
plt.gca().yaxis.set_major_formatter(formatter)

plt.show()

You can just plot the log values, and the log of the formatters. It is much simpler ...

plt.hist(np.log(x), bins=50, normed=True)
plt.xticks(np.log(z), z)

You can also use a base 2 log if you wish ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM