我有以下代码:
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 字符串来评估 c
.这将给出任何国家的货币,而不是使用 $ 符号。但是它似乎没有评估 f-string,你能建议任何可能的替代方案吗?
最佳答案
tick string formatter需要一个带有 x
的格式字符串(和可选 pos
):
The field used for the tick value must be labeled
x
and the field used for the tick position must be labeledpos
.
这意味着我们需要评估
c
但不是 x
, 所以:c
使用格式字符串:ax.yaxis.set_major_formatter(c + '{x:1.2f}')
f
),其中 x
的大括号被转义( c
的单大括号, x
的双大括号):ax.yaxis.set_major_formatter(f'{c}{{x:1.2f}}')
关于python - yaxis.set_major_formatter 中的 f 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69065509/