更改轴而不更改数据(Python) [英] Changing axis without changing data (Python)

查看:84
本文介绍了更改轴而不更改数据(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绘制一些数据,删除由该数据创建的轴,并用不同比例的轴替换它们?

How could I plot some data, remove the axis created by that data, and replace them with axis of a different scale?

说我有类似的东西:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([0,5])
plt.ylim([0,5])
plt.plot([0,1,2,3,4,5])
plt.show()

这将以5x5的方式在两条轴上绘制一条范围从0到5的直线.我想删除0到5轴,并说用-25到25轴替换它.这只会改变轴,但我不想移动任何数据,即看起来与原始图相同,只是轴不同.我意识到可以简单地通过移动数据来完成此操作,但我不希望更改数据.

This plots a line in a 5x5 plot with ranges from 0 to 5 on both axis. I would like to remove the 0 to 5 axis and say replace it with a -25 to 25 axis. This would just change the axis, but I don't want to move any of the data, i.e., it looks identical to the original plot just with different axis. I realize this can be simply done by shifting the data, but I do not wish to alter the data.

推荐答案

您可以使用 plt.xticks 查找标签的位置,然后设置标签到位置值的5倍.底层数据不会改变;仅标签.

You could use plt.xticks to find the location of the labels, and then set the labels to 5 times the location values. The underlying data does not change; only the labels.

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([0,5])
plt.ylim([0,5])
plt.plot([0,1,2,3,4,5])
locs, labels = plt.xticks()
labels = [float(item)*5 for item in locs]
plt.xticks(locs, labels)
plt.show()

收益

或者,您可以更改代码格式器:

Alternatively, you could change the ticker formatter:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

N = 128
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(range(N+1))
plt.xlim([0,N])
plt.ylim([0,N])
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: ('%g') % (x * 5.0)))
plt.show()

这篇关于更改轴而不更改数据(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆