Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

508
Views
Cómo agregar una etiqueta x y una etiqueta y compartidas a un gráfico creado con pandas plot

Uno puede crear subparcelas fácilmente desde un marco de datos usando pandas:

 import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20)

¿Cómo se agregarían ahora las etiquetas x e y al gráfico resultante? Aquí se explica para una sola parcela. Entonces, si quisiera agregar etiquetas a una trama secundaria en particular, podría hacerlo:

 ax[1][0].set_xlabel('my_general_xlabel') ax[0][0].set_ylabel('my_general_ylabel') plt.show()

Eso da:

ingrese la descripción de la imagen aquí

¿Cómo se agregarían las etiquetas para que estén centradas y no solo se refieran a una fila/columna?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Las etiquetas X e Y están vinculadas a ejes en matplotlib. Por lo tanto, tiene poco sentido usar los comandos xlabel o ylabel con el fin de etiquetar varias subparcelas.

Sin embargo, lo que es posible es crear un texto simple y colocarlo en la posición deseada. fig.text(x,y, text) coloca algo de texto en las coordenadas x e y en las coordenadas de la figura, es decir, la esquina inferior izquierda de la figura tiene las coordenadas (0,0) y la esquina superior derecha (1,1) .

 import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True) fig=axes[0,0].figure fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center") fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90) plt.show()

ingrese la descripción de la imagen aquí

El inconveniente de esta solución es que las coordenadas de dónde colocar el texto deben configurarse manualmente y pueden depender del tamaño de la figura.

over 4 years ago · Santiago Trujillo Report

0

Otra solución: cree una subparcela grande y luego establezca las etiquetas comunes. Esto es lo que tengo.

ingrese la descripción de la imagen aquí

El código fuente está debajo.

 import pandas as pd import matplotlib.pyplot as plt fig = plt.figure() axarr = fig.add_subplot(221) df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", ax=axarr, subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20) # Create a big subplot ax = fig.add_subplot(111, frameon=False) # hide tick and tick label of the big axes plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off') ax.set_xlabel('my_general_xlabel', labelpad=10) # Use argument `labelpad` to move label downwards. ax.set_ylabel('my_general_ylabel', labelpad=20) plt.show()
over 4 years ago · Santiago Trujillo Report

0

Esto creará un eje 111 invisible donde puede establecer las etiquetas generales x e y:

 import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=12) fig = ax[0][0].get_figure() # getting the figure ax0 = fig.add_subplot(111, frame_on=False) # creating a single axes ax0.set_xticks([]) ax0.set_yticks([]) ax0.set_xlabel('my_general_xlabel', labelpad=25) ax0.set_ylabel('my_general_ylabel', labelpad=45) # Part of a follow up question: Modifying the fontsize of the titles: for i,axi in np.ndenumerate(ax): axi.set_title(axi.get_title(),{'size' : 16})

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!