Pandas to MatPlotLib with Dollar Signs

微笑、不失礼 提交于 2019-12-10 18:26:44

问题


Given the following data frame:

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

I'd like to create a bar chart in MatPlotLib but I can't seem to get the dollar signs to show up correctly.

Here's what I have:

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('')

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).

Thanks in advance!


回答1:


To specify the xticklabels, pass tick_label=x to plt.bar.

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('$', '\$')

For example,

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()


Alternatively, you could use 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()



来源:https://stackoverflow.com/questions/38151646/pandas-to-matplotlib-with-dollar-signs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!