matplotlib 打印文本不会左对齐

0mkxixxg  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(91)

我试图获得红点的值(对于'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()

bzzcjhmw

bzzcjhmw1#

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

字符串


的数据

相关问题