pandas 到MatPlotLib与美元符号 [英] Pandas to MatPlotLib with Dollar Signs
问题描述
给出以下数据框:
import pandas as pd
df=pd.DataFrame({'A':['$0-$20','$20+']})
df
A
0 0−20
1 $20+
我想在MatPlotLib中创建一个条形图,但是我似乎无法正确显示美元符号.
I'd like to create a bar chart in MatPlotLib but I can't seem to get the dollar signs to show up correctly.
这就是我所拥有的:
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('')
如果使用df.A.values.tolist()
,我可以使标签显示更好",但这只是纠正了格式.
我希望每个标签以预期的原始格式(带有美元符号)显示在每个栏中.
I can get the labels to display "better" if I use df.A.values.tolist()
, but that just corrects the format.
I'd like each label to display under each bar with the intended original format (with dollar signs).
提前谢谢!
推荐答案
要指定xtick标签,请将tick_label=x
传递给plt.bar
.
To specify the xticklabels, pass tick_label=x
to plt.bar
.
Matplotlib使用 TeX标记的子集来解析标签
语言.美元
符号指示数学模式的开始(和结束).所以成对的裸美元符号是
意外吞咽.当前,没有方法禁用mathtex解析.因此,为防止美元符号被解释为数学标记,请替换
裸$
与\$
:
Matplotlib parses labels using a subset of the TeX markup
language. Dollar
signs indicate the beginning (and end) of math mode. So pairs of bare dollar signs are
getting unintentionally swallowed. Currently, there is no a way to disable mathtex parsing. So to prevent the dollar signs from being interpreted as math markup, replace the
bare $
with \$
:
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()
或者,您可以使用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()
这篇关于 pandas 到MatPlotLib与美元符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!