You can read a leaderboard on a website. You cannot bend it, filter it, or chart it, and that is its own particular frustration, wanting a baseball number you can see and having no idea how to get it off the page and into your own hands. pybaseball closes that gap. It is a free, open-source Python library that pulls Major League data (season stats, Statcast pitch-by-pitch, leaderboards) straight into a pandas DataFrame, where it becomes yours to do anything with.
This is a from-scratch tutorial. By the end you will have installed the library, pulled the 2025 batting leaderboard, filtered it down to the hitters who actually played, and drawn a clean bar chart of the top ten by OPS: the exact chart below, produced by about twenty lines of code. No API key, no scraping, no spreadsheet exports. Ten minutes, start to finish.
Install it
pybaseball lives on PyPI, so installation is a single command. Open a terminal and run:
pip install pybaseball
That pulls in pandas, requests, and matplotlib as dependencies, which means you already have everything you need to fetch data and plot it. If you keep your projects in virtual environments, and you should, activate yours first. The version this tutorial was written against is 2.2.7; you can confirm what you got by running python -c "import pybaseball; print(pybaseball.__version__)". Anything in the 2.x line behaves the same way for what follows.
The imports
Three lines set the stage. We import matplotlib for plotting and pybaseball under the short alias pyb. The first line silences a thicket of harmless deprecation and SSL warnings that some of the backends emit: cosmetic, but it keeps your console readable.
import warnings; warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
import pybaseball as pyb
That is the entire setup. Everything else is two function calls and a chart.
Pull the leaderboard
Here is the single most important decision in this whole exercise, and it is one most tutorials get wrong. pybaseball can pull season batting lines from two different sources: FanGraphs (via batting_stats()) and Baseball-Reference (via batting_stats_bref()). They return similar-looking tables. They do not behave the same way for automated scripts.
FanGraphs aggressively rate-limits and frequently blocks programmatic access. Call batting_stats() a couple of times in quick succession and you will start collecting timeouts, 403s, and empty frames, not because your code is wrong, but because the server decided a robot was knocking. The Baseball-Reference and Statcast backends do not do this. They are the reliable choice, and they are what this tutorial uses throughout. So we reach for the Baseball-Reference backend, specifically batting_stats_range, the date-windowed sibling of batting_stats_bref, which reads the same daily-totals page but lets us bracket the pull ourselves:
df = pyb.batting_stats_range("2025-03-18", "2025-09-28")
df = df[df["PA"] >= 300].copy()
top = df.sort_values("OPS", ascending=False).head(10)
Three lines, three ideas. The first hands you every 2025 player-batting line as a DataFrame: every hitter, dozens of columns, indexed and ready. Passing explicit dates matters more than it looks: those two dates are opening day and the final day of the regular season, and windowing the pull that way is what keeps October out of your season totals. Ask bref for “2025” as a whole and it happily counts postseason games too, which quietly pushes the leaders’ plate appearances past what any official leaderboard will show you. The second line filters: df["PA"] >= 300 keeps only players with at least 300 plate appearances, which throws out September call-ups and bench arms whose tiny samples would otherwise clutter the top of a rate-stat list. The .copy() is a small good habit: it tells pandas you mean to keep this slice as its own object and quietly avoids a SettingWithCopyWarning later. The third line sorts by OPS, highest first, and keeps the top ten.
Note that the column names (PA, OPS, OBP, SLG, HR) come straight from Baseball-Reference’s own headers. If you ever forget what a table offers, print(df.columns.tolist()) spells it out.
Chart the top ten
A DataFrame is useful; a picture is persuasive. We will draw a horizontal bar chart, which is the right shape for a ranked list of names because the labels read left-to-right like a leaderboard should. The setup grabs the names and OPS values out of the top frame and reverses both lists with [::-1]; matplotlib draws the first bar at the bottom, so reversing puts the best hitter on top where the eye expects him.
fig, ax = plt.subplots(figsize=(8.0, 5.4))
names = top["Name"].tolist()[::-1]
vals = [float(v) for v in top["OPS"].tolist()][::-1]
ax.barh(range(len(names)), vals)
ax.set_yticks(range(len(names)))
ax.set_yticklabels(names, fontsize=10)
ax.set_xlabel("OPS (on-base plus slugging)")
ax.set_title("2025 OPS leaders, pulled with pybaseball", loc="left")
for i, v in enumerate(vals):
ax.text(v + .004, i, "%.3f" % v, va="center", fontsize=9)
plt.show()
The barh call draws the bars; the two set_yticks/set_yticklabels lines attach player names to them. The little for loop is the touch that makes it feel finished: it writes each OPS value as text just past the end of its bar, formatted to three decimals with "%.3f", so a reader gets both the visual length and the exact figure. Swap plt.show() for fig.savefig("ops_leaders.png") if you would rather write the chart to a file. Run the script and the figure below is what you get.
Reading what you pulled
The numbers are worth a glance, because they are a good sanity check that the pull worked. Aaron Judge sits on top at a 1.144 OPS: 53 home runs against a .457 on-base percentage and a .688 slugging mark, a line that barely looks real. Add those two rounded components by hand and you get 1.145, and that is the figure our Stats API piece reports from its own totals; Baseball-Reference computes OPS from the unrounded rates and lands a point lower. A one-point disagreement between two sources computing the same stat from the same season is normal, and worth expecting rather than explaining away. Shohei Ohtani follows at 1.014, and rookie Nick Kurtz crashes the list at 1.002 on the strength of a .619 slug in under 500 plate appearances. Here is the full top ten exactly as the script saved it:
| Player | PA | HR | OBP | SLG | OPS |
|---|---|---|---|---|---|
| Aaron Judge | 679 | 53 | 0.457 | 0.688 | 1.144 |
| Shohei Ohtani | 727 | 55 | 0.392 | 0.622 | 1.014 |
| Nick Kurtz | 489 | 36 | 0.383 | 0.619 | 1.002 |
| George Springer | 586 | 32 | 0.399 | 0.560 | 0.959 |
| Cal Raleigh | 705 | 60 | 0.359 | 0.589 | 0.948 |
| Ronald Acuña Jr. | 412 | 21 | 0.417 | 0.518 | 0.935 |
| Kyle Schwarber | 724 | 56 | 0.365 | 0.563 | 0.928 |
| Juan Soto | 715 | 43 | 0.396 | 0.525 | 0.921 |
| Kyle Stowers | 457 | 25 | 0.368 | 0.544 | 0.912 |
| Will Smith | 436 | 17 | 0.404 | 0.497 | 0.901 |
That table was not typed by hand. It is the same top DataFrame, written out column by column, which is the whole point of getting data into Python in the first place. Once it is a frame, charting it, tabulating it, joining it to another season, or filtering it by team are all one line away.
The 2026 run-through: the same code, one season later
A tutorial like this one is only worth something if its code still runs. So on December 1, 2026, with the 2026 regular season finished (it ran from March 25 to September 27, by the MLB Stats API schedule), we ran the three lines above again on the same pybaseball 2.2.7, changing nothing but the dates:
df = pyb.batting_stats_range("2026-03-25", "2026-09-27")
df = df[df["PA"] >= 300].copy()
top = df.sort_values("OPS", ascending=False).head(10)
It worked with no other change. The pull came back with 664 player rows and 28 columns, 267 of them hitters with at least 300 plate appearances. Yordan Alvarez leads at 1.033 (42 home runs, a .432 on-base percentage and a .601 slugging mark in 692 plate appearances), the only hitter with 300 or more plate appearances over 1.000. Pete Crow-Armstrong is a long way back in second at .943, and Juan Soto third at .908 in just 482 plate appearances. The chart below comes from the same plotting code.
| Player | PA | HR | OBP | SLG | OPS | Stats API OPS |
|---|---|---|---|---|---|---|
| Yordan Alvarez | 692 | 42 | 0.432 | 0.601 | 1.033 | 1.033 |
| Pete Crow-Armstrong | 726 | 45 | 0.372 | 0.570 | 0.943 | 0.942 |
| Juan Soto | 482 | 27 | 0.393 | 0.515 | 0.908 | 0.908 |
| Willson Contreras | 535 | 27 | 0.386 | 0.516 | 0.901 | 0.902 |
| Ben Rice | 667 | 41 | 0.363 | 0.534 | 0.897 | 0.897 |
| James Wood | 623 | 30 | 0.388 | 0.503 | 0.891 | 0.891 |
| Shohei Ohtani | 618 | 30 | 0.377 | 0.512 | 0.889 | 0.889 |
| Junior Caminero | 702 | 42 | 0.360 | 0.524 | 0.885 | 0.884 |
| Pete Alonso | 700 | 43 | 0.363 | 0.522 | 0.884 | 0.885 |
| Elly De La Cruz | 636 | 30 | 0.365 | 0.515 | 0.880 | 0.880 |
Checking it against a second source. A pull you can’t check is a pull you have to trust, so we asked the MLB Stats API’s 2026 season hitting totals for the same ten players, matched by player ID. Plate appearances and home runs agree for all ten. OPS agrees exactly for six and by one point for the other four (Crow-Armstrong .943 here and .942 there, Willson Contreras .901 and .902, Junior Caminero .885 and .884, Pete Alonso .884 and .885). In all four the Stats API’s OPS is exactly this table’s OBP plus SLG as printed, while Baseball-Reference adds the unrounded rates: the same rounding story as Judge’s 1.144 against 1.145 above.
The window still matters. To see what the two dates keep out, we also ran batting_stats_bref(2026), which asks Baseball-Reference for March 1 through November 30. It returns the same 664 players, but six of the ten leaders come back with more plate appearances, 135 extra among them, all from the postseason: Caminero goes from 702 to 759, Shohei Ohtani from 618 to 650, Ben Rice from 667 to 689, and Alvarez, Crow-Armstrong and Contreras each gain 8. That table is a real thing, but it isn’t the regular season, and no official leaderboard will match it.
The next step, in 2026. The Statcast pull this page points to needs a player’s MLB Advanced Media ID, and the Baseball-Reference table already carries it, in a column pybaseball adds called mlbID. So the 2026 leader’s every tracked pitch is two more lines away, with the same two dates:
leader = top.iloc[0]
sc = pyb.statcast_batter("2026-03-25", "2026-09-27", int(leader["mlbID"]))
bb = sc[sc["type"] == "X"] # balls in play
print(len(sc), len(bb), bb["launch_speed"].mean(), bb["launch_speed"].max())
For Alvarez (ID 670541) that returned 2,752 pitches from 158 games, every one of them a regular-season pitch, and 452 balls in play. Their average exit velocity was 94.4 mph and the hardest was 118.5; 54.0% left the bat at 95 mph or more, Statcast’s hard-hit line. The rows hold 42 home runs, the same 42 Baseball-Reference has. And the 452 balls in play equal the count on Baseball Savant’s own 2026 expected-statistics leaderboard, which lists him at 691 plate appearances and a .602 slugging mark: one plate appearance and one point of slugging off the other two sources. Three sources, three slightly different bookkeepers, all within a hair of each other.
One function we didn’t run. playerid_lookup, the name-to-ID function in the next section, downloads the Chadwick Bureau’s player register as a zip file from a GitHub archive address, and GitHub’s robots.txt asks automated agents not to fetch archive paths. So this run-through skips it and reads the ID from the mlbID column instead. For a single season’s leaders that is all you need. What this run can’t promise: it is one pull on one day, and Baseball-Reference and Savant both revise their numbers now and then, so a later run may move a decimal.
Where to go next
Two functions unlock most of the rest of the library. The first is playerid_lookup, which translates a human name into the various ID numbers the data sources use:
pyb.playerid_lookup("judge", "aaron")
That returns a small DataFrame with, among other columns, key_mlbam (the MLB Advanced Media ID). You need that ID for the second function, statcast_batter, which pulls a single hitter’s every tracked pitch and batted ball, complete with exit velocity, launch angle, and hit coordinates. That is the raw material for a spray chart, and it is exactly the next tutorial in this series: building a spray chart from Statcast data picks up precisely where this one leaves off, turning statcast_batter output into a picture of where a hitter sprays the ball.
A short troubleshooting note
Three things trip up newcomers. First, rate limits: if a call hangs or returns nothing, you are almost certainly hitting a FanGraphs endpoint; switch to the Baseball-Reference or Statcast equivalents, and do not hammer any source in a tight loop. Second, caching: pybaseball can remember responses so you are not re-downloading the same data on every run, which is both faster and friendlier to the servers. Enable it once with from pybaseball import cache; cache.enable() and repeated pulls come back instantly. Third, an empty DataFrame usually means a season hasn’t started or a name was misspelled, not that anything is broken: check your arguments before you check your code.
The bottom line
The distance between “I wish I could chart that” and an actual chart is, it turns out, about twenty lines of Python and one good decision about which backend to trust. Install pybaseball, lean on the Baseball-Reference and Statcast sources, get your data into a DataFrame, and the entire toolbox of pandas and matplotlib opens up behind it. You now have the leaderboard in your hands: bend it however you like.
Sources & Further Reading
- Leaderboard data: Baseball-Reference, pulled via pybaseball’s Baseball-Reference daily backend (version 2.2.7), windowed to the 2025 regular season (March 18 to September 28; postseason excluded). Numbers retrieved July 2026; computed for this article from that source.
- The 2026 run-through, pulled December 1, 2026 with pybaseball 2.2.7: Baseball-Reference’s daily batting page for March 25 to September 27, 2026 (the page
batting_stats_rangereads), checked against the MLB Stats API’s 2026 season hitting totals and 2026 regular-season schedule; Statcast rows from Baseball Savant’s Statcast search (the endpointstatcast_battercalls), and the ball-in-play count checked against Savant’s 2026 expected-statistics leaderboard (read October 20, 2026). - Baseball Savant: the Statcast source behind
statcast_batterand the spray-chart follow-up. - FanGraphs: an alternate stats backend, noted here for the rate-limiting caveat discussed above.