It really has nothing to do with the ratings.
I worked for an advertising agency in college. For some shows you can expect to pay 3-5 times as much to advertise on the show than average. Most companies are looking to advertise to 14-30 years old. As companies like to brain-wash you while your brain is still forming and this is the age period where most people develop brand loyalty.
So the age and demographics of the users is really big. But it isn't as easy as slicing the pie and saying 60% of the viewers are under 30 and we have 10 million viewers, so that means 6 million in your demographic, so pay us $xxx based on those users. There is also the "cool" factor. In that a show may have a really intense user base, a show may have a lot of press, or whatever. Then it becomes basically a bidding war unless your agency locked in a long-term contract.
This shows how old I am but the best example of this that I know is "Party of Five". Pretty lame teenie bopper drama (IMO) and was one of the worst rated shows on TV. But almost all of its viewers where under 25, it had a cult following and its cast was getting tons of press. I remember we had to pay out the ass to get our stuff on the show based on industry averages at the time.
Another important factor is network backing. You can kind of tell this by the slot a new show gets and the advertising. If the network is all in on a show and they like it, well they will spend more money for another season even if the previous season "lost money".
There are also tons of intangibles related to costs and crew. You have a lot of actors crossing over between movies and TV so there is competition and unknown cost of keeping actors. You have foreign viewers to think about as some shows do really well overseas and some don't translate.