yaxis.set_major_formatter 中的 f-string

3
我有以下的代码:
import pandas as pd
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import yfinance as yf
import matplotlib.ticker as mtick
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
                               AutoMinorLocator)
import currency
import warnings

warnings.filterwarnings("ignore")

start = datetime.date(2000,1,1)
end = datetime.date.today()


stock =  'goog'
fig, ax = plt.subplots(dpi=300, figsize =(8,4) )
data = web.DataReader(stock, 'yahoo', start, end)
data['Close'].plot()
ax.tick_params(axis='y', colors='midnightblue')

ax.tick_params(axis='x', colors="k")
pg = yf.Ticker(stock)
# sn = pg.info['shoName']
sn = pg.info['shortName']

b = pg.info['currency']
c = currency.symbol(f"{b}")
ax.set_ylabel(f"Price ({pg.info['currency']})")
ax.xaxis.grid(False, which='minor')
ax.yaxis.set_major_formatter('${x:1.2f}')
ax.margins(x=0)
# plt.savefig(f"{sn} {end.strftime('%d - %b%Y')}", bbox_inches='tight', dpi = 500)
print(sn)
print('datetime date =', start)
plt.show()
print()

我面临的问题是ax.yaxis.set_major_formatter('${x:1.2f}')。我需要获取一个f-string来评估c,这将给出任何国家的货币,而不是使用$符号。然而它似乎无法评估f-string,请建议任何可能的替代方案?
1个回答

1

tick字符串格式化程序需要一个带有x(和可选的pos)的格式字符串:

用于刻度值的字段必须标记为x,用于刻度位置的字段必须标记为pos

这意味着我们需要评估c但不是x,因此:

  • Either concatenate c with the format string:

    ax.yaxis.set_major_formatter(c + '{x:1.2f}')
    
  • Or pass an evaluated f-string (add f) where x's braces are escaped (single braces for c, double braces for x):

    ax.yaxis.set_major_formatter(f'{c}{{x:1.2f}}')
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接