Python Matplotlib:绘图文本不会左对齐

时间:2015-11-11 22:29:49

标签: python matplotlib

我正在尝试将红点的值(对于' y2'的值)绘制到点的左侧。我正在使用ha =' left'但无济于事。我尝试了以下两个方法:

for a,b in zip(ind, y2):
    plt.text(a, b, str(b), fontsize=14, color='black', va='center', ha='left)

#OR:
for i, text in enumerate(y2):
    ax.annotate(str(text), (ind[i],y2[i]), ha='left')

以下是完整的代码:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
df0=pd.read_csv('sample1.csv')

import matplotlib.pyplot as plt

# You typically want your plot to be ~1.33x wider than tall.
# Common sizes: (10, 7.5) and (12, 9)
fig, ax = plt.subplots(1, 1, figsize=(12, 9))
plt.xticks(ind, x_axis, fontsize=14)
#Set y-axis font size
plt.yticks(fontsize=12)
x_axis = ['a','b','c']
y_axis = [2,8,10]

y2 = [3, 5, 9.5]

# Remove the plot frame lines. They are unnecessary here.
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

#0 = 'a', 1 = 'b, 2 = 'c'
ind = np.arange(len(x_axis))


#remove axis ticks save for left (y-axis):
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off')         # ticks along the top edge are off


plt.tick_params(
    axis='y',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    right='off')

plt.title('Super Awesome Title Goes Here\n'
          'and Is Continued Here', fontsize=18, va='center')
#Plot dots, cyan circles, no edges, transparency = 0.7 (1 is opaque))
# larger circles
plt.plot(ind, y_axis, 'co', markeredgecolor='none', alpha=1, markersize=40)
#plt.axis(0,10,0,3)

plt.plot(ind, y2, 'ro', markeredgecolor='none', alpha=.7, markersize=40)

#a and b are "where" to plot the label, str(b) is what to plot for the label
#add spaces to put label to the right
for a,b in zip(ind, y_axis):
    plt.text(a, b, "     "+str(b), fontsize=14, color='black', va='center')

for a,b in zip(ind, y2):
    plt.text(a, b, str(b), fontsize=14, color='black', va='center', ha='left')

    #Cell padding between categories
plt.xlim([min(ind) - 0.25, max(ind) + 0.25])
plt.ylim([0, max(y_axis) + 2])
plt.show()

1 个答案:

答案 0 :(得分:5)

hava参数指定文本边界框的哪些边将与指定的x,y坐标对齐。如果您希望文本显示在点的左侧,则需要根据边界框的右侧边缘对齐它:

from matplotlib import pyplot as  plt

fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(0, 0, '+', ms=60)
ax.text(0, 0, 'align by top right corner', ha='right', va='top', fontsize=22)
ax.text(0, 0, 'align by bottom left corner', ha='left', va='bottom', fontsize=22)
ax.set_axis_off()
plt.show()

enter image description here