python - yaxis.set_major_formatter 中的 f 字符串

标签 python python-3.x matplotlib f-string

我有以下代码:

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 labeled pos.


这意味着我们需要评估 c但不是 x , 所以:
  • 连接 c使用格式字符串:
    ax.yaxis.set_major_formatter(c + '{x:1.2f}')
    
  • 或者传递一个已评估的 f 字符串(添加 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/

    相关文章:

    python - 随机生成张量的 Tensorflow 转置

    python - 哪一种数据加载方法最适合性能?

    python - 如何根据用户对第一个问题的输入提示用户 x 次

    python - 使用 scipy python 中的 curve_fit 函数

    python - Matplotlib - 财务量叠加

    python - 使用 pandas 根据另一个数据帧的行值填充列值

    python - 我的密码存储在 Django admin 的电子邮件字段内

    python - 选择两个数组中的值

    python - 按值排序字典,然后按键

    matplotlib - 将集合添加到多个轴?