matplot lib y轴间隔与美元符号

时间:2016-04-06 05:10:39

标签: python matlab matplotlib

我有以下代码来生成一个显示x轴年份的图表,以及y轴的美元数量。如何格式化我的y轴以显示间隔,如$ 4,000,000,$ 8,000,000,$ 12,000,000 ......

现在,y轴在左上方显示0.2,0.4和1e7。

    from matplotlib import pyplot as plt
    ...
    plt.figure(figsize=(8,4))
    plt.plot(x_values, y_values)
    plt.ylabel('Amount')
    ...
    plt.savefig(img_path)

2 个答案:

答案 0 :(得分:0)

Matlab示例

% Years on x axis
x = 2010:2016;

% Dollar amount on y axis
y = linspace(4000000,8000000,length(x));

% Plot and save the tick values that Matlab generates
plot(x,y);
yTicks = get(gca,'YTick');

% Turn ticks into non-exponential values
a = textscan(num2str(yTicks),'%f');

% Format into strings representing dollar amount with delimiter etc. 
newYTickLabels = Sep1000Str(a{1});

% Set your new ticklabels
set(gca,'YTickLabel',newYTickLabels)

Sep1000Str()的位置:

function output = Sep1000Str(a)
n = length(a);
for k = 1:n
    S = sprintf('$%.2f', a(k));
    S(2, length(S) - 6:-3:2) = ',';
    S = {transpose(S(S ~= char(0)))};
    output(k) = S;
end

答案 1 :(得分:0)

您可以使用matplotlib FormatStrFormatter

x_values = [2011,2012,2013,2014,2015,2016,2017] #list of years
y_values = np.linspace(4e6,10e6,len(x_values)) #y_values with same size as x

fig, ax = plt.subplots(figsize=(8,4))
ax.plot(x_values, y_values)

formatter = ticker.FormatStrFormatter('$%0.1f') #declaring the formatter with the $ sign and y_values with 1 decimalplace
ax.yaxis.set_major_formatter(formatter)

for tick in ax.yaxis.get_major_ticks():
    tick.label1.set_visible(True) #make your yvalues visible on the plot

plt.show()