They write about what they know. 2pac does not write about working on a farm. Shakespeare (Sir Francis Bacon) wrote about what he saw in his world. Also these people are/were incredibly talented. Shakespeare paints with words like DaVinci painted with oils. It was his medium.
2pac is honest about what he writes about. How many writers try to polish up where they came from so they won't be judged?
The short answer is: life experience and research mixed with a healthy dose of creativity and artistry. Additionally, a good writer is not afraid to take risks. Two creative risk takers among current authors are Annie Proulx and Cormac McCarthy.