0

I have tried to change 0.0 to 0 at the start of the x-axis when I have my graph.

My numerical data are:

x = 0.115, 0.234, 0.329, 0.443, 0.536, 0.654, 0.765, 0.846

y = 5.598, 7.6942, 9.1384, 11.2953, 12.4065, 15.736, 21.603, 31.4367

s = 0.05, 0.1, 0.16, 0.4, 0.32, 0.17, 0.09, 1.2

The original data does not have x = 0, y = 0. I make the commands to add it and make the graph automatically. But the graph starts at 0.0 on the x-axis. How do I change 0.0 to 0 without affecting the rest of the numbers?

I have studied the following links ... but still have not succeeded ... Modify tick label text pyplot remove the digits of zero ( start from 0 not 0.00)

The commands I have are:

import pandas as pd
import matplotlib.pyplot as plt

datos = pd.read_csv('.name.csv')
print(datos)

datosSM1 = datos[0:0]
datosSM1.loc[0] = 0
datosSM2 = datos[0:]

datosSM = pd.concat([datosSM1, datosSM2])
print(datosSM)

x = datosSM['x']
y = datosSM['y']
ys = datosSM['s']

plt.errorbar(x,y, fmt = 'ko', label = 'datos', 
         yerr = ys, ecolor='r' )
plt.axis([0, x.max()+0.02, 0, y.max()+(y.max()/10)])

plt.show()

I really appreciate your help and attention.

2 Answers2

1

Really thank you very much, and excellent suggestions. I think your code is better than the alternative I just wrote ...

    ax = plt.axes()
def format_func(value, tick_number):
    N = value
    if N == 0:
        return "0"
    else:
        return "{0:0.2}".format(N)

ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))

Thank you

  • This is the standard way to solve your problem and should be more reliable than @Valdi_Bo 's answer. – Joooeey May 31 '20 at 18:20
  • You can just write `def format_func(N, tick_number)` and avoid the reassignment `N = value`. – Joooeey May 31 '20 at 18:21
0

To modify a selected label (actually its text), try the below code:

# Prepend first row with zeroes
datosSM = pd.concat([pd.DataFrame({'x': 0, 'y': 0, 's': 0}, index=[0]),
    datos], ignore_index=True)
# Drawing
fig, ax = plt.subplots()  # Will be needed soon
plt.errorbar(datosSM.x, datosSM.y, yerr=datosSM.x, fmt='ko', label='datos', ecolor='r')
plt.axis([0, datosSM.x.max() + 0.02, 0, datosSM.y.max() + (datosSM.y.max() / 10)])
fig.canvas.draw()  # Needed to get access to label texts
# Get label texts
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = '0'    # Modify the selected label
ax.set_xticklabels(labels)
plt.show()

One additional improvement in the above code is a more concise way to generate a Dataframe with prepended row with zeroes.

Another improvement is that you don't need to "extract" individual columns. You can pass existing columns of your DataFrame.

The result is:

enter image description here

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41