python-3.x - 带有美元符号的 Pandas 到 MatPlotLib

标签 python-3.x pandas matplotlib axis-labels dollar-sign

给定以下数据框:

import pandas as pd
df=pd.DataFrame({'A':['$0-$20','$20+']})
df
    A
0   0−20
1   $20+

我想在 MatPlotLib 中创建一个条形图,但我似乎无法正确显示美元符号。

这是我所拥有的:

import matplotlib.pyplot as plt
import numpy as np

y=df.B
x=df.A
ind=np.arange(len(x))
fig, ax = plt.subplots(1, 1, figsize = (2,2))

plt.bar(ind, y, align='center', width=.5, edgecolor='none', color='grey')
ax.patch.set_facecolor('none')
ax.patch.set_alpha(0)
ax.set_ylim([0,5])
ax.set_xlabel(x,fontsize=12,rotation=0,color='grey')
ax.set_xticklabels('')
ax.set_yticklabels('')

enter image description here

如果我使用 df.A.values.tolist(),我可以让标签显示得“更好”,但这只会更正格式。 我希望每个标签都以预期的原始格式(带有美元符号)显示在每个栏下。

提前致谢!

最佳答案

要指定 xticklabels,将 tick_label=x 传递给 plt.bar

Matplotlib 使用 TeX markup language 的子集解析标签.美元 符号表示数学模式的开始(和结束)。所以成对的裸美元符号是 不小心被吞了。目前,没有办法disable mathtex parsing .所以为了防止美元符号被解释为数学标记,替换 裸 $\$:

df['A'] = df['A'].str.replace('$', '\$')

例如,

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': ['$0-$20', '$20+'], 'B': [10,20]})
df['A'] = df['A'].str.replace('$', '\$')

y = df['B']
x = df['A']
ind = np.arange(len(x))
fig, ax = plt.subplots(1, 1, figsize=(2, 2))

plt.bar(ind, y, 
        tick_label=x, 
        align='center', width=.5, edgecolor='none', 
        color='grey')
plt.show()

enter image description here


或者,您可以使用 df.plot(kind='bar'):

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': ['$0-$20', '$20+'], 'B': [10,20]})
df['A'] = df['A'].str.replace('$', '\$')

fig, ax = plt.subplots(1, 1, figsize=(2, 2))

df.plot(kind='bar', x='A', y='B',
        align='center', width=.5, edgecolor='none', 
        color='grey', ax=ax)
plt.xticks(rotation=25)
plt.show()

enter image description here

关于python-3.x - 带有美元符号的 Pandas 到 MatPlotLib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38151646/

相关文章:

python - 在 Python3 中操作 JSON 配置文件内变量的最佳方法

python - Pandas 向前填充具有特定值的时间戳列(1 秒)

python - 如何使用 Pandas html 函数解析表格?

Python:将多行用户输入写入文本文件

python - 多个元组条件的计数器

python - Matplotlib 中的线端样式

python - Matplotlib 补丁 - 圆看起来是椭圆

python - 光标在 Tkinter 中的 matplotlib Canvas 上

python - 如何为同一组中的每个值分配一个序列号? Python

python - 从系列列表创建数据框