Axis numerical offset in matplotlib

余生颓废 提交于 2019-12-12 04:26:00

问题


I'm plotting something with matplotlib and it looks like this:

I can't seem to figure out why the x-axis is offset like it is...It looks like it's saying, 'whatever you read from me, add 2.398e9 to it for the actual x value'.

This is not quite what I want...Can I make it take only the first 4 digits, instead?

This is representing frequency, so I'd like to see something that reads:

2000 or 2400 or 2800....I can add the 'MHz' part in the axis title...But, this is unreadable at a glance.

Is this doing this because it's trying to make decisions on how to truncate long data?

Here's the code for the plotting:

plt.title(file_name +' at frequency '+ freq + 'MHz')
plt.xlabel('Frequency')
plt.ylabel('Conducted Power (dBm)')
plt.grid(True)
plt.plot(data['x'],data['y'])
#plt.axis([min(data['x']),max(data['x']),min(data['y'],max(data['y']))])
plt.savefig(file_name+'_'+freq)
print('plot written!')
#plt.show()
plt.close('all')

回答1:


You need to import certain formatters from matplotlib.ticker. Here is the full documentation to ticker

from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))

Once you have set this to your plot likewise, you should be able to see the +2.398e9 disappear.

In general to avoid scientific notation, use the following:

ax.get_xaxis().get_major_formatter().set_scientific(False)



回答2:


If you don't want to play the formatting game and would rather just display values directly in MHz, then you could simply rescale your data to be in MHz instead of Hz. Something like

data['x'] /= 1000

and then add the 'MHz' to your axis label.



来源:https://stackoverflow.com/questions/39253742/axis-numerical-offset-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!