简体   繁体   English

如何创建 y 轴上的值列表,而不必在 Python 中创建 plot 图形?

[英]How can I create a list of the values on the y-axis without having to plot a graph in Python?

I have a piece of code that plots a random walk with a specified number of bins on my y-axis.我有一段代码在我的 y 轴上用指定数量的 bin 绘制随机游走。 Is there a way in Python to replicate/recreate the values on my y-axis, without having to plot the graph? Python 中有没有办法复制/重新创建我的 y 轴上的值,而不必 plot 图表? Below is the code I've been working on and the method I've tried is to divide the min-max range by the number of wanted bins and thereafter create a list with these values.下面是我一直在处理的代码,我尝试过的方法是将 min-max 范围除以想要的 bin 数量,然后创建一个包含这些值的列表。 However, I find my method far from optimal and not close to the results I get by using the below code.但是,我发现我的方法远非最佳,也不接近使用以下代码获得的结果。

I am greatful for any help on this matter!我非常感谢在这件事上提供任何帮助!

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

dims = 1
step_n = 2000
step_set = [-1, 0, 1]
origin = np.zeros((1,dims))
random.seed(30)
step_shape = (step_n,dims)
steps = np.random.choice(a=step_set, size=step_shape)
path = np.concatenate([origin, steps]).cumsum(0)


# create subplot
fig, ax = plt.subplots(1,1, figsize=(20, 11))
img = ax.plot(path)
plt.locator_params(axis='y', nbins=20)
y_values = ax.get_yticks() # y_values is a numpy array with my y values 

I am not sure, if I understood your problem correctly.我不确定,如果我正确理解了您的问题。 Matplotlib defines the differences between the ticks in a way, that I assume are mostly multiples of 5. But a general approach could be, to calculate a padding based on the bins you want and add/subtract it. Matplotlib 以某种方式定义了刻度之间的差异,我认为这主要是 5 的倍数。但一般的方法可能是,根据您想要的 bin 计算填充并添加/减去它。 For your given example the following gives the same result as ax.get_yticks()对于您给定的示例,以下给出与ax.get_yticks()相同的结果

bins = 19
padding = np.ceil((np.max(path) - np.min(path)) / bins)

np.linspace(np.min(path) - padding, np.max(path) + padding, bins, dtype=np.int32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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